package com.atmob.voiceai.module.result;

import android.os.Parcelable;

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.logging.AtmobLog;
import com.atmob.common.runtime.ActivityUtil;
import com.atmob.common.runtime.ContextUtil;
import com.atmob.voiceai.R;
import com.atmob.voiceai.data.api.bean.UserVoiceBean;
import com.atmob.voiceai.data.api.bean.VoiceListBean;
import com.atmob.voiceai.data.api.response.VoiceListResponse;
import com.atmob.voiceai.data.repositories.VoiceAIRepository;
import com.atmob.voiceai.utils.DateUtil;
import com.atmob.voiceai.utils.MediaStoreHelper;
import com.atmob.voiceai.utils.ShareUtils;
import com.atmob.voiceai.utils.ToastUtil;
import com.atmob.voiceai.utils.VoiceFileUtil;

import java.io.File;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import javax.inject.Inject;

import atmob.okhttp3.OkHttpClient;
import atmob.reactivex.rxjava3.annotations.NonNull;
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 dagger.hilt.android.lifecycle.HiltViewModel;

@HiltViewModel
public class VoiceResultViewModel extends BaseViewModel {


    private final VoiceAIRepository voiceAIRepository;
    private final MutableLiveData<Boolean> isPlay = new MutableLiveData<>();
    private final MutableLiveData<Long> totalDuration = new MutableLiveData<>();
    private final MutableLiveData<Long> currentDuration = new MutableLiveData<>();
    private final SingleLiveEvent<?> refreshAudioCurrentProgress = new SingleLiveEvent<>();
    private final MutableLiveData<List<VoiceListBean>> voiceList = new MutableLiveData<>();

    private final MutableLiveData<UserVoiceBean> userVoiceBean = new MutableLiveData<>();
    private final OkHttpClient okHttpClient;
    private boolean isSeekbarChanging;
    private Timer timer;

    private boolean downloadFileDisposable;

    @Inject
    public VoiceResultViewModel(VoiceAIRepository voiceAIRepository, OkHttpClient okHttpClient) {
        this.voiceAIRepository = voiceAIRepository;
        this.okHttpClient = okHttpClient;
        refreshVoiceRecommendList();
    }

    public LiveData<List<VoiceListBean>> getVoiceList() {
        return voiceList;
    }

    public LiveData<Boolean> getIsPlay() {
        return isPlay;
    }

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

    public LiveData<Long> getCurrentDuration() {
        return currentDuration;
    }

    public LiveData<Long> getTotalDuration() {
        return totalDuration;
    }

    public LiveData<UserVoiceBean> getResultBean() {
        return userVoiceBean;
    }


    public void setVoicePlay(boolean isPlay) {
        this.isPlay.setValue(isPlay);
    }

    public void setCurrentDuration(long duration) {
        if (duration >= 0) {
            currentDuration.setValue(duration);
        }
    }

    public void setTotalDuration(long duration) {
        if (duration >= 0) {
            totalDuration.setValue(duration);
        }
    }

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


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

    public void onBackClick() {
        ActivityUtil.getTopActivity().finish();
    }

    private void refreshVoiceRecommendList() {
        voiceAIRepository.requestVoiceList("").subscribe(new SingleObserver<VoiceListResponse>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                addDisposable(d);
            }

            @Override
            public void onSuccess(@NonNull VoiceListResponse voiceListResponse) {
                voiceList.setValue(voiceListResponse.getVoiceList());
            }

            @Override
            public void onError(@NonNull Throwable e) {

            }
        });
    }

    public void setRecommendVoice(VoiceListBean voiceListBean) {
        voiceAIRepository.setRecommendClickBean(voiceListBean);
    }


    public void onSaveClick() {
        UserVoiceBean userVoiceBean = getResultBean().getValue();
        if (userVoiceBean == null) {
            return;
        }
        if (downloadFileDisposable) {
            return;
        }
        VoiceFileUtil.getVoiceFile(okHttpClient, userVoiceBean.getVoiceUrl())
                .map(file -> {
                    MediaStoreHelper.saveToSharedStorage(MediaStoreHelper.TYPE_AUDIO, file, file.getName());
                    return file;
                })
                .subscribe(new SingleObserver<File>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                        downloadFileDisposable = true;
                    }

                    @Override
                    public void onSuccess(@NonNull File file) {
                        downloadFileDisposable = false;
                        ToastUtil.show(R.string.voice_save_success, ToastUtil.LENGTH_SHORT);
                        AtmobLog.d("VoiceResultViewModel", "onSuccess: " + file.getAbsolutePath());
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        downloadFileDisposable = false;
                        ToastUtil.show(R.string.voice_save_error, ToastUtil.LENGTH_SHORT);
                        AtmobLog.d("VoiceResultViewModel", "onError: " + e.getMessage());
                    }
                });
    }

    private String getVoiceFileName() {
        //月日年时分毫秒+3位随机数
        return "VoiceAI_" + DateUtil.formatNormalDate("ddMMyyyyHHmmssSSS", System.currentTimeMillis()) + (new Random().nextInt(900) + 100) + ".mp3";
    }

    public void onShareClick() {
        UserVoiceBean userVoiceBean = getResultBean().getValue();
        if (userVoiceBean == null) {
            return;
        }
        if (downloadFileDisposable) {
            return;
        }
        VoiceFileUtil.getVoiceFile(okHttpClient, userVoiceBean.getVoiceUrl())
                .map(file -> {
                    ShareUtils.shareAudioFile(ActivityUtil.getTopActivity(), file);
                    return file;
                })
                .subscribe(new SingleObserver<File>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                        downloadFileDisposable = true;
                    }

                    @Override
                    public void onSuccess(@NonNull File file) {
                        downloadFileDisposable = false;
                        AtmobLog.d("VoiceResultViewModel", "Share-onSuccess: " + file.getAbsolutePath());
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        downloadFileDisposable = false;
                        ToastUtil.show(R.string.voice_file_get_error, ToastUtil.LENGTH_SHORT);
                        AtmobLog.d("VoiceResultViewModel", "Share-onError: " + e.getMessage());
                    }
                });
    }


    public void setVoiceBean(UserVoiceBean userVoiceBean) {
        this.userVoiceBean.setValue(userVoiceBean);
    }


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