package com.datarecovery.master.utils;

import android.os.Build;
import android.view.Gravity;

import androidx.activity.ComponentActivity;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;

import com.atmob.common.data.KVUtils;
import com.atmob.common.runtime.ContextUtil;
import com.datarecovery.master.R;
import com.datarecovery.master.data.consts.EventId;
import com.datarecovery.master.dialog.PermissionDialog;
import com.datarecovery.master.handler.EventHelper;
import com.datarecovery.master.utils.xfile.XFilePermission;

import atmob.reactivex.rxjava3.annotations.NonNull;
import atmob.reactivex.rxjava3.core.Single;
import atmob.reactivex.rxjava3.core.SingleObserver;
import atmob.reactivex.rxjava3.core.SingleSource;
import atmob.reactivex.rxjava3.disposables.Disposable;
import atmob.reactivex.rxjava3.functions.Function;
import atmob.rxjava.utils.RxJavaUtil;

public class FilePermissionHelper {

    private static final String ANDROID_DATA_PERMISSION_SUCCESS = "android_data_permission_success";

    Disposable disposable;

    public void requestDataFilePermission(ComponentActivity activity, NextStepCallback stepCallback) {
        Single.just(Build.VERSION.SDK_INT)
                .flatMap((Function<Integer, SingleSource<Integer>>) sdkInt -> {
                    //判断是否有所有文件权限
                    boolean result = PermissionUtil.hasFilePermission();
                    if (!result) {
                        return (SingleSource<Integer>) observer -> activity.runOnUiThread(() -> {
                            PermissionDialog requestManageDialog = new PermissionDialog(activity);
                            requestManageDialog.setDialogTitle(R.string.request_manage_permission_title)
                                    .setDialogContent(R.string.request_manage_permission_content)
                                    .setTitleGravity(Gravity.START)
                                    .setContentGravity(Gravity.START)
                                    .setSureText(R.string.teaching_limit)
                                    .setOnDialogClickListener(new PermissionDialog.OnDialogClickListener() {
                                        @Override
                                        public void onClickSure() {
                                            PermissionUtil.requestWriteStoragePermission(activity, new PermissionUtil.PermissionCallback() {
                                                @Override
                                                public void onPermissionGranted() {
                                                    requestManageDialog.dismiss();
                                                    observer.onSuccess(sdkInt);

                                                    GalleryBackupManager.getInstance().onPermissionGranted();
                                                    EventHelper.report(EventId.EVENT_3000101);
                                                }

                                                @Override
                                                public void onPermissionDenied() {
                                                    EventHelper.report(EventId.EVENT_3000102);
                                                }
                                            });
                                        }

                                        @Override
                                        public void onClickCancel() {
                                            observer.onError(new CancelException());
                                        }
                                    });
                            requestManageDialog.setOnShowListener(dialog -> EventHelper.report(EventId.EVENT_3000100));
                            requestManageDialog.show();
                        });
                    } else {
                        return Single.just(sdkInt);
                    }
                })
                .flatMap((Function<Integer, SingleSource<Integer>>) sdkInt -> {
                    if (sdkInt >= Build.VERSION_CODES.TIRAMISU || KVUtils.getDefault().getBoolean(ANDROID_DATA_PERMISSION_SUCCESS, false)) {
                        return Single.just(sdkInt);
                    }
                    boolean dataFolder = XFilePermission.hasAndroidDataPermission(ContextUtil.getContext());
                    if (!dataFolder) {
                        return observer -> activity.runOnUiThread(() -> {
                            PermissionDialog requestAndroidDataDialog = new PermissionDialog(activity);
                            requestAndroidDataDialog.setDialogTitle(R.string.request_android_data_permission_title)
                                    .setDialogContent(R.string.request_android_data_permission_content)
                                    .setCancelText(R.string.wait_moment)
                                    .setSureText(R.string.teaching_limit)
                                    .setOnDialogClickListener(new PermissionDialog.OnDialogClickListener() {
                                        @Override
                                        public void onClickSure() {
                                            XFilePermission.requestAndroidDataPermission(activity, new XFilePermission.PermissionCallback() {
                                                @Override
                                                public void onPermissionGranted() {
                                                    requestAndroidDataDialog.dismiss();
                                                    observer.onSuccess(sdkInt);
                                                    //部分手机无法授权data目录，选择任意目录记录为通过，下次不再检查
                                                    KVUtils.getDefault().putBoolean(ANDROID_DATA_PERMISSION_SUCCESS, true);
                                                    EventHelper.report(EventId.EVENT_3000101);
                                                }

                                                @Override
                                                public void onPermissionDenied() {
                                                    EventHelper.report(EventId.EVENT_3000102);
                                                }
                                            });
                                        }

                                        @Override
                                        public void onClickCancel() {
                                            observer.onError(new CancelException());
                                        }
                                    });
                            requestAndroidDataDialog.setOnShowListener(dialog -> EventHelper.report(EventId.EVENT_3000100));
                            requestAndroidDataDialog.show();
                        });
                    } else {
                        return Single.just(sdkInt);
                    }
                })
                .compose(RxJavaUtil.SingleSchedule.io2Main())
                .subscribe(new SingleObserver<Integer>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        disposable = d;
                    }

                    @Override
                    public void onSuccess(@NonNull Integer sdkInt) {
                        if (stepCallback != null) stepCallback.onNextStep();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if (e instanceof CancelException) {
                            if (stepCallback != null) stepCallback.onCancel();
                        }
                    }
                });
        activity.getLifecycle().addObserver(new LifecycleEventObserver() {
            @Override
            public void onStateChanged(@androidx.annotation.NonNull LifecycleOwner lifecycleOwner, @androidx.annotation.NonNull Lifecycle.Event event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    if (disposable != null && !disposable.isDisposed()) {
                        disposable.dispose();
                    }
                    activity.getLifecycle().removeObserver(this);
                }
            }
        });
    }

    public interface NextStepCallback {
        void onNextStep();

        void onCancel();
    }

    private static class CancelException extends Exception {
    }
}
