package com.datarecovery.master.module.videorecover;

import static com.datarecovery.master.data.consts.EventId.EVENT_3000004;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;

import com.atmob.app.lib.base.BaseViewModel;
import com.atmob.app.lib.livedata.SingleLiveEvent;
import com.atmob.common.data.KVUtils;
import com.atmob.common.runtime.ContextUtil;
import com.datarecovery.master.R;
import com.datarecovery.master.data.consts.AdFuncId;
import com.datarecovery.master.data.consts.EventId;
import com.datarecovery.master.data.repositories.DeviceFuncRepository;
import com.datarecovery.master.handler.EventHelper;
import com.datarecovery.master.sdk.ad.AtmobAdHelper;
import com.datarecovery.master.sdk.bugly.BuglyHelper;
import com.datarecovery.master.utils.FileUtil;
import com.datarecovery.master.utils.FilesSearch;
import com.datarecovery.master.utils.MediaStoreHelper;
import com.datarecovery.master.utils.ReverseArrayList;
import com.datarecovery.master.utils.ToastUtil;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import atmob.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import atmob.reactivex.rxjava3.annotations.NonNull;
import atmob.reactivex.rxjava3.core.Single;
import atmob.reactivex.rxjava3.core.SingleObserver;
import atmob.reactivex.rxjava3.disposables.Disposable;
import atmob.rxjava.utils.RxJavaUtil;
import dagger.hilt.android.lifecycle.HiltViewModel;


@HiltViewModel
public class VideoRecoverViewModel extends BaseViewModel {

    private final String IS_SHOW_VIDEO_HINT = "isShowVideoHint";
    private final long SCANNING_COUNTDOWN = 1000 * 60 * 6;

    private final long SCANNING_IS_TRIAL_COUNTDOWN = 1000 * 5;
    private final LiveData<String> selectedCountTxt;
    private final MutableLiveData<String> detectedLastFileName = new MutableLiveData<>();
    private final MutableLiveData<Boolean> checkAll = new MutableLiveData<>(false);

    private final List<FilesSearch.DocumentFile> videoList = new ReverseArrayList<>();
    private final List<FilesSearch.DocumentFile> selectList = new ArrayList<>();
    private final MutableLiveData<List<FilesSearch.DocumentFile>> detectedVideoList = new MutableLiveData<>();
    private final MutableLiveData<List<FilesSearch.DocumentFile>> selectedList = new MutableLiveData<>(selectList);
    private final MutableLiveData<Boolean> showTrialView = new MutableLiveData<>();
    private final SingleLiveEvent<?> scrollTop = new SingleLiveEvent<>();
    private final SingleLiveEvent<Boolean> showScanDialogEvent = new SingleLiveEvent<>();
    private final SingleLiveEvent<Boolean> showLoadingEvent = new SingleLiveEvent<>();
    private final DeviceFuncRepository deviceFuncRepository;
    private final MutableLiveData<Boolean> isShowHint = new MutableLiveData<>();
    private final SingleLiveEvent<Void> showUnlockEvent = new SingleLiveEvent<>();
    private Disposable scanDisposable;


    @Inject
    public VideoRecoverViewModel(DeviceFuncRepository deviceFuncRepository) {
        this.deviceFuncRepository = deviceFuncRepository;
        selectedCountTxt = Transformations.map(selectedList, list -> {
            if (list == null || list.isEmpty()) {
                return ContextUtil.getContext().getString(R.string.export);
            }
            return ContextUtil.getContext().getString(R.string.export_count, list.size());
        });
        if (KVUtils.getDefault().getBoolean(IS_SHOW_VIDEO_HINT, true)) {
            isShowHint.setValue(true);
        }
    }

    public LiveData<String> getDetectedLastFileName() {
        return detectedLastFileName;
    }

    public LiveData<Boolean> getShowTrialView() {
        return showTrialView;
    }

    public LiveData<Boolean> getIsShowHint() {
        return isShowHint;
    }

    public LiveData<List<FilesSearch.DocumentFile>> getDetectedVideoList() {
        return detectedVideoList;
    }

    public LiveData<?> getScrollTop() {
        return scrollTop;
    }

    public LiveData<Boolean> getShowScanDialogEvent() {
        return showScanDialogEvent;
    }

    public LiveData<List<FilesSearch.DocumentFile>> getSelectedList() {
        return selectedList;
    }

    public LiveData<Boolean> getCheckAll() {
        return checkAll;
    }

    public LiveData<String> getSelectedCountTxt() {
        return selectedCountTxt;
    }

    public LiveData<Boolean> getShowLoadingEvent() {
        return showLoadingEvent;
    }

    public LiveData<?> getShowUnlockEvent() {
        return showUnlockEvent;
    }

    public void startVideoScanning() {
        if (scanDisposable != null && !scanDisposable.isDisposed()) {
            return;
        }
        FilesSearch.search(ContextUtil.getContext(), FilesSearch.DocumentFile.VIDEO)
                .take(SCANNING_COUNTDOWN, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<FilesSearch.DocumentFile>>() {
                    @Override
                    public void onSubscribe(Subscription s) {
                        s.request(Integer.MAX_VALUE);
                        scanDisposable = Disposable.fromSubscription(s);
                        addDisposable(scanDisposable);
                        showScanDialogEvent.setValue(true);
                        videoList.clear();
                    }

                    @Override
                    public void onNext(List<FilesSearch.DocumentFile> documentFiles) {
                        if (documentFiles == null) {
                            return;
                        }
                        for (FilesSearch.DocumentFile documentFile : documentFiles) {
                            detectedLastFileName.setValue(documentFile.getName());
                        }
                        videoList.addAll(documentFiles);
                        detectedVideoList.setValue(videoList);
                        scrollTop.call();
                    }

                    @Override
                    public void onError(Throwable t) {
                        showScanDialogEvent.setValue(false);
                    }

                    @Override
                    public void onComplete() {
                        showScanDialogEvent.setValue(false);
                    }
                });
    }

    public void onCheckAllClick(boolean isCheck) {
        EventHelper.report(EventId.EVENT_3000006);
        checkAll.setValue(isCheck);
        for (FilesSearch.DocumentFile videoFile : videoList) {
            videoFile.setCheck(isCheck);
        }
        if (isCheck) {
            selectList.clear();
            selectList.addAll(videoList);
        } else {
            selectList.clear();
        }
        this.selectedList.setValue(selectList);
    }

    public void cancelScan() {
        if (scanDisposable != null && !scanDisposable.isDisposed()) scanDisposable.dispose();
        showScanDialogEvent.setValue(false);
    }

    public void onExportClick() {
        if (selectList.isEmpty()) {
            return;
        }
        showUnlockEvent.call();
    }

    public void doExport() {
        Single.just(selectList.size())
                .map(oldSize -> {
                    Iterator<FilesSearch.DocumentFile> iterator = selectList.iterator();
                    int errorCount = 0;
                    Exception exception = null;
                    while (iterator.hasNext()) {
                        FilesSearch.DocumentFile item = iterator.next();
                        try {
                            MediaStoreHelper.saveToSharedStorage(MediaStoreHelper.TYPE_VIDEO, item.newInputStream(), FileUtil.getCreateFileName(MediaStoreHelper.TYPE_VIDEO, item.getName()));
                            item.setCheck(false);
                            iterator.remove();
                        } catch (Exception throwable) {
                            errorCount++;
                            exception = throwable;
                            BuglyHelper.postCatchedException(new Exception("视频导出:", throwable));
                        }
                    }
                    if (errorCount == oldSize) {
                        throw new Exception("导出失败" + (exception == null ? "" : ":" + exception.getMessage()));
                    } else if (errorCount > 0) {
                        throw new Exception("部分导出失败" + ":" + exception.getMessage());
                    }
                    return errorCount;
                })
                .compose(RxJavaUtil.SingleSchedule.io2Main())
                .subscribe(new SingleObserver<Integer>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        showLoadingEvent.setValue(true);
                        addDisposable(d);
                    }

                    @Override
                    public void onSuccess(@NonNull Integer integer) {
                        showLoadingEvent.setValue(false);
                        selectedList.setValue(selectList);
                        checkAll.setValue(false);
                        ToastUtil.show(R.string.export_success, ToastUtil.LENGTH_SHORT);
                        AtmobAdHelper.showInterstitial(AdFuncId.INTERSTITIAL_RECOVER_SUCCESS, null);
                        EventHelper.report(EVENT_3000004);
                    }

                    @Override
                    public void onError(@NonNull Throwable throwable) {
                        showLoadingEvent.setValue(false);
                        selectedList.setValue(selectList);
                        ToastUtil.show(throwable.getMessage(), ToastUtil.LENGTH_SHORT);
                    }
                });
    }

    public void setItemCheck(@NonNull FilesSearch.DocumentFile file) {
        file.setCheck(!file.isCheck());
        if (file.isCheck()) {
            selectList.add(file);
        } else {
            selectList.remove(file);
        }
        selectedList.setValue(selectList);
    }

    public void closeHintClick() {
        KVUtils.getDefault().putBoolean(IS_SHOW_VIDEO_HINT, false);
        isShowHint.setValue(false);
    }
}
