package com.datarecovery.master.module.preview;

import android.net.Uri;

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

import com.atmob.app.lib.base.BaseViewModel;
import com.atmob.app.lib.livedata.SingleLiveEvent;
import com.atmob.common.runtime.ContextUtil;
import com.datarecovery.master.R;
import com.datarecovery.master.data.consts.EventId;
import com.datarecovery.master.handler.EventHelper;
import com.datarecovery.master.sdk.bugly.BuglyHelper;
import com.datarecovery.master.utils.BoxingUtil;
import com.datarecovery.master.utils.FileUtil;
import com.datarecovery.master.utils.FilesSearch;
import com.datarecovery.master.utils.ImageDeepDetector;
import com.datarecovery.master.utils.MediaStoreHelper;
import com.datarecovery.master.utils.ToastUtil;

import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.inject.Inject;

import atmob.rxjava.utils.RxJavaUtil;
import dagger.hilt.android.lifecycle.HiltViewModel;

@HiltViewModel
public class PreviewViewModel extends BaseViewModel {

    public static WeakReference<?> weakReference;
    private final MutableLiveData<String> title = new MutableLiveData<>();
    private final MutableLiveData<Uri> previewUri = new MutableLiveData<>();
    private final MutableLiveData<Boolean> isPlaying = new MutableLiveData<>();
    private final SingleLiveEvent<?> refreshAudioCurrentProgress = new SingleLiveEvent<>();
    private final SingleLiveEvent<?> clickMediaPlayerEvent = new SingleLiveEvent<>();
    private final MutableLiveData<Integer> seekBarProgress = new MutableLiveData<>();
    private final MutableLiveData<Boolean> isPlayStart = new MutableLiveData<>();
    private final MutableLiveData<ImageDeepDetector.ImageFile> currentImageFile = new MutableLiveData<>();
    private final SingleLiveEvent<?> showUnlockEvent = new SingleLiveEvent<>();
    private List<ImageDeepDetector.ImageFile> imagePreviewList;
    private int type;
    private FilesSearch.DocumentFile currentFileFile;
    private int position;
    private Timer timer;
    private boolean isSeekbarChanging;

    private boolean isSurfaceCreated;

    @Inject
    public PreviewViewModel() {
    }

    public LiveData<?> getClickMediaPlayerEvent() {
        return clickMediaPlayerEvent;
    }

    public void setSurfaceCreated(boolean surfaceCreated) {
        isSurfaceCreated = surfaceCreated;
    }

    public LiveData<Integer> getSeekBarProgress() {
        return seekBarProgress;
    }

    public LiveData<?> getRefreshAudioCurrentProgress() {
        return refreshAudioCurrentProgress;
    }

    public void setSeekbarChanging(boolean seekbarChanging) {
        isSeekbarChanging = seekbarChanging;
    }

    public MutableLiveData<Boolean> getIsPlayStart() {
        return isPlayStart;
    }

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

    public void setIsPlayStart(boolean isPlayStart) {
        this.isPlayStart.setValue(isPlayStart);
    }

    public LiveData<ImageDeepDetector.ImageFile> getCurrentImageFile() {
        return currentImageFile;
    }

    public int getPosition() {
        return position;
    }

    public void setPosition(int position) {
        if (type == PreviewActivity.TYPE_IMG) {
            if (position != -1 && imagePreviewList != null && position < imagePreviewList.size()) {
                ImageDeepDetector.ImageFile imageFile = imagePreviewList.get(position);
                currentImageFile.setValue(imageFile);
            }

        }
    }

    public List<ImageDeepDetector.ImageFile> getImagePreviewList() {
        return imagePreviewList;
    }

    public LiveData<String> getTitle() {
        return title;
    }

    public int getType() {
        return type;
    }

    public LiveData<Uri> getPreviewUri() {
        return previewUri;
    }

    public LiveData<Boolean> getIsPlaying() {
        return isPlaying;
    }

    public void setIsPlaying(boolean isPlaying) {
        this.isPlaying.setValue(isPlaying);
    }

    public void setPreviewData(@PreviewActivity.Type int type, int position) {
        this.type = type;
        this.position = position;
        switch (type) {
            case PreviewActivity.TYPE_AUDIO:
                dealAudioInit();
                break;
            case PreviewActivity.TYPE_IMG:
                dealImageInit();
                break;
            case PreviewActivity.TYPE_VIDEO:
                dealVideoInit();
                break;
        }
    }

    private void dealVideoInit() {
        title.setValue(ContextUtil.getContext().getString(R.string.preview_video));
        if (weakReference != null) {
            this.currentFileFile = (FilesSearch.DocumentFile) weakReference.get();
            setUri(currentFileFile.getUri());
        }
    }

    private void dealAudioInit() {
        title.setValue(ContextUtil.getContext().getString(R.string.preview_audio));
        if (weakReference != null) {
            this.currentFileFile = (FilesSearch.DocumentFile) weakReference.get();
            setUri(currentFileFile.getUri());
        }
    }

    public Uri getUri() {
        if (type == PreviewActivity.TYPE_IMG) {
            ImageDeepDetector.ImageFile value = currentImageFile.getValue();
            if (value != null) {
                return value.getUri();
            } else {
                return null;
            }
        } else if (type == PreviewActivity.TYPE_AUDIO || type == PreviewActivity.TYPE_VIDEO) {
            if (currentFileFile != null) {
                return currentFileFile.getUri();
            } else {
                return null;
            }
        }
        return null;
    }

    public void setUri(Uri uri) {
        this.previewUri.setValue(uri);
    }

    private void dealImageInit() {
        title.setValue(ContextUtil.getContext().getString(R.string.preview_img));
        if (weakReference != null) {
            this.imagePreviewList = (List<ImageDeepDetector.ImageFile>) weakReference.get();
        }
    }

    public void setIsPlayStart() {
        if (BoxingUtil.boxing(this.isPlayStart.getValue())) {
            return;
        }
        this.isPlayStart.setValue(true);
    }

    public void onExportClick() {
        showUnlockEvent.call();

        switch (getType()) {
            case PreviewActivity.TYPE_IMG:
                EventHelper.report(EventId.EVENT_3000504);
                break;
            case PreviewActivity.TYPE_VIDEO:
                break;
            case PreviewActivity.TYPE_AUDIO:
                EventHelper.report(EventId.EVENT_3000803);
                break;
        }

    }

    public void doExport() {
        RxJavaUtil.doInBackground(() -> {
                    if (type == PreviewActivity.TYPE_IMG) {
                        ImageDeepDetector.ImageFile value = currentImageFile.getValue();
                        if (value == null) {
                            return false;
                        }
                        MediaStoreHelper.saveToSharedStorage(MediaStoreHelper.TYPE_IMAGE, value.newInputStream(), FileUtil.getCreateFileName(MediaStoreHelper.TYPE_IMAGE, value.getName()));
                    } else if (type == PreviewActivity.TYPE_AUDIO) {
                        if (currentFileFile == null) {
                            return false;
                        }
                        MediaStoreHelper.saveToSharedStorage(MediaStoreHelper.TYPE_AUDIO, currentFileFile.newInputStream(), FileUtil.getCreateFileName(MediaStoreHelper.TYPE_AUDIO, currentFileFile.getName()));
                    }
                    return true;
                }
                , o -> ToastUtil.show(R.string.export_success, ToastUtil.LENGTH_SHORT)
                , throwable -> {
                    if (type == PreviewActivity.TYPE_IMG) {
                        BuglyHelper.postCatchedException(new Exception("预览-图片导出：", throwable));
                    } else if (type == PreviewActivity.TYPE_AUDIO) {
                        BuglyHelper.postCatchedException(new Exception("预览-音频导出：", throwable));
                    }
                    ToastUtil.show(throwable.getMessage(), ToastUtil.LENGTH_SHORT);

                }
        );
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (weakReference != null) {
            weakReference.clear();
        }
        if (timer != null) timer.cancel();
    }

    public void startMediaTimer() {
        if (timer != null) {
            return;
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (type == PreviewActivity.TYPE_AUDIO) {
                    if (isSeekbarChanging) {
                        return;
                    }
                    refreshAudioCurrentProgress.postValue(null);
                }
            }
        }, 0, 100);
    }

    public void setSeekbarTo(int progress) {
        this.seekBarProgress.setValue(progress);
    }

    public void onVideoClick() {
        if (isSurfaceCreated) {
            setIsPlayStart();
            clickMediaPlayerEvent.call();
        }
    }

    public void onAudioPlayClick() {
        clickMediaPlayerEvent.call();
    }
}