package com.atmob.voiceai.module.voiceai;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Pair;

import androidx.annotation.ColorInt;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
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.ActivityUtil;
import com.atmob.common.runtime.ContextUtil;
import com.atmob.voiceai.R;
import com.atmob.voiceai.data.api.bean.TypeListBean;
import com.atmob.voiceai.data.api.bean.VoiceListBean;
import com.atmob.voiceai.data.api.response.VoiceListResponse;
import com.atmob.voiceai.data.api.response.VoiceTypeResponse;
import com.atmob.voiceai.data.consts.EventId;
import com.atmob.voiceai.data.repositories.MemberRepository;
import com.atmob.voiceai.data.repositories.VoiceAIRepository;
import com.atmob.voiceai.handlers.EventHandler;
import com.atmob.voiceai.helper.ErrorHelper;
import com.atmob.voiceai.module.generating.VoiceGeneratingActivity;
import com.atmob.voiceai.module.setting.SettingActivity;
import com.atmob.voiceai.module.subscription.SubscriptionPageActivity;
import com.atmob.voiceai.utils.BoxingUtil;
import com.atmob.voiceai.utils.SpannableUtil;
import com.atmob.voiceai.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

import atmob.reactivex.rxjava3.annotations.NonNull;
import atmob.reactivex.rxjava3.core.SingleObserver;
import atmob.reactivex.rxjava3.disposables.Disposable;
import dagger.hilt.android.lifecycle.HiltViewModel;

@HiltViewModel
public class VoiceAIViewModel extends BaseViewModel {

    private final String LAST_GENERATE_TEXT = "last_generate_text";

    private final LiveData<CharSequence> voiceProbationTxt;
    private final MutableLiveData<String> voicePrintTxt = new MutableLiveData<>();
    private final LiveData<String> voicePrintLimitTxt;

    @ColorInt
    private final int freeTxtColor;
    private final VoiceAIRepository voiceAIRepository;


    private final MutableLiveData<Boolean> showQueryLoading = new MutableLiveData<>(true);
    private final MutableLiveData<List<TypeListBean>> voiceTypeList = new MutableLiveData<>();
    private final MutableLiveData<Pair<List<VoiceListBean>, VoiceListBean>> voiceDetailList = new MutableLiveData<>();
    private final MemberRepository memberRepository;

    private VoiceListBean choiceVoiceBean;

    private final SingleLiveEvent<VoiceListBean> scrollToBean = new SingleLiveEvent<>();

    private final SingleLiveEvent<VoiceListBean> playExampleVoice = new SingleLiveEvent<>();
    private final SingleLiveEvent<Integer> scrollToTabPosition = new SingleLiveEvent<>();
    private final SingleLiveEvent<?> showGenerateAd = new SingleLiveEvent<>();
    private final SingleLiveEvent<VoiceListBean> notifyBean = new SingleLiveEvent<>();

    private String currentTypeId;
    private Disposable voiceListDisposable;

    Observer<VoiceListBean> recommendObserver;
    Observer<Object> cloneObserver;
    Observer<Integer> useCloneObserver;

    @Inject
    public VoiceAIViewModel(MemberRepository memberRepository, VoiceAIRepository voiceAIRepository) {
        this.memberRepository = memberRepository;
        this.voiceAIRepository = voiceAIRepository;
        voicePrintLimitTxt = Transformations.map(voicePrintTxt, txt -> {
            int length = 0;
            if (!TextUtils.isEmpty(txt)) {
                length = txt.length();
            }
            return length + "/200";
        });
        freeTxtColor = ContextUtil.getApplication().getResources().getColor(R.color.voice_free_crux_txt_color);
        voicePrintTxt.setValue(KVUtils.getDefault().getString(LAST_GENERATE_TEXT, ""));
        voiceProbationTxt = Transformations.map(voiceAIRepository.getAdFreeGenerateNumber(), number -> {
            if (number == null || BoxingUtil.boxing(memberRepository.getIsMember().getValue())) {
                return "";
            }
            return SpannableUtil.getSpannableStringBuilder(ContextUtil.getContext().getString(R.string.voice_ai_get_free_number, number), String.valueOf(number), freeTxtColor, false);
        });
        iniVoiceAI();
    }

    public LiveData<Boolean> getShowQueryLoading() {
        return showQueryLoading;
    }

    public LiveData<Integer> getScrollToTabPosition() {
        return scrollToTabPosition;
    }

    public LiveData<VoiceListBean> getNotifyBean() {
        return notifyBean;
    }

    public LiveData<VoiceListBean> getPlayExampleVoice() {
        return playExampleVoice;
    }

    public LiveData<?> getShowGenerateAd() {
        return showGenerateAd;
    }

    public LiveData<Pair<List<VoiceListBean>, VoiceListBean>> getVoiceDetailList() {
        return voiceDetailList;
    }

    public LiveData<List<TypeListBean>> getVoiceTypeList() {
        return voiceTypeList;
    }

    public LiveData<VoiceListBean> getScrollToBean() {
        return scrollToBean;
    }

    public LiveData<Integer> getAdFreeGenerateNumber() {
        return voiceAIRepository.getAdFreeGenerateNumber();
    }

    public LiveData<Boolean> isMember() {
        return memberRepository.getIsMember();
    }

    public LiveData<CharSequence> getVoiceProbationTxt() {
        return voiceProbationTxt;
    }

    public LiveData<String> getVoicePrintLimitTxt() {
        return voicePrintLimitTxt;
    }

    public MutableLiveData<String> getVoicePrintTxt() {
        return voicePrintTxt;
    }

    public void clearPrintTxt() {
        voicePrintTxt.setValue("");
    }


    public void onGenerateClick() {
        EventHandler.report(EventId.homegenerate_001);
        String content = voicePrintTxt.getValue();
        if (TextUtils.isEmpty(content)) {
            ToastUtil.show(R.string.voice_ai_print_hint, ToastUtil.LENGTH_SHORT);
            return;
        }
        if (choiceVoiceBean == null) {
            ToastUtil.show(R.string.voice_ai_no_choice, ToastUtil.LENGTH_SHORT);
            return;
        }
        if (BoxingUtil.boxing(isMember().getValue())) {
            requestGenerateVoice();
            return;
        }
        if (choiceVoiceBean.isHasPro()) {
            SubscriptionPageActivity.start(ActivityUtil.getTopActivity());
            return;
        }
        if (BoxingUtil.boxing(voiceAIRepository.getAdFreeGenerateNumber().getValue()) > 0) {
            showGenerateAd.call();
            return;
        }
        SubscriptionPageActivity.start(ActivityUtil.getTopActivity());
    }

    private void requestGenerateVoice() {
        voiceAIRepository.requestTextToSpeech(choiceVoiceBean, voicePrintTxt.getValue());
        VoiceGeneratingActivity.start(ActivityUtil.getTopActivity());
    }


    private void iniVoiceAI() {
        requestVoiceTypeList();
        fromOtherRecommendSelectVoice();
    }

    private void fromOtherRecommendSelectVoice() {
        if (recommendObserver != null) {
            voiceAIRepository.getRecommendClickBean().removeObserver(recommendObserver);
        }
        recommendObserver = bean -> {
            if (bean == null) {
                return;
            }
            voicePrintTxt.setValue(bean.getContent());
            List<TypeListBean> typeList = voiceTypeList.getValue();
            if (typeList == null || typeList.isEmpty()) {
                return;
            }
            if (Objects.equals(this.currentTypeId, String.valueOf(bean.getTypeId())) || Objects.equals(String.valueOf(typeList.get(0).getId()), this.currentTypeId)) {
                //在当前列表项或当前列表项为第一个（一般为ALL）
                scrollToListPosition(bean.getId());
            } else {
                //将列表项设置为第一个
                scrollToTabPosition.setValue(0);
                refreshVoiceList(String.valueOf(typeList.get(0).getId()), bean);
            }
        };
        voiceAIRepository.getRecommendClickBean().observeForever(recommendObserver);
        if (cloneObserver != null) {
            voiceAIRepository.getCloneExecuteSuccess().removeObserver(cloneObserver);
        }
        cloneObserver = o -> {
            //判断当前选中tab是否第一个
            List<TypeListBean> typeList = voiceTypeList.getValue();
            if (typeList == null || typeList.isEmpty()) {
                return;
            }
            if (Objects.equals(String.valueOf(typeList.get(0).getId()), currentTypeId)) {
                requestVoiceList(currentTypeId, null);
            }
        };
        voiceAIRepository.getCloneExecuteSuccess().observeForever(cloneObserver);
        if (useCloneObserver != null) {
            voiceAIRepository.getUseClonedVoiceEvent().removeObserver(useCloneObserver);
        }
        useCloneObserver = id -> {
            List<TypeListBean> typeList = voiceTypeList.getValue();
            if (typeList == null || typeList.isEmpty()) {
                return;
            }
            int typeId = typeList.get(0).getId();
            if (Objects.equals(String.valueOf(typeId), currentTypeId)) {
                scrollToListPosition(BoxingUtil.boxing(id));
            } else {
                scrollToTabPosition.setValue(0);
                refreshVoiceList(String.valueOf(typeId), null);
            }
        };
        voiceAIRepository.getUseClonedVoiceEvent().observeForever(useCloneObserver);
    }

    public void scrollToListPosition(int id) {
        Pair<List<VoiceListBean>, VoiceListBean> voiceDetail = voiceDetailList.getValue();
        if (voiceDetail == null || voiceDetail.first == null) {
            return;
        }
        for (VoiceListBean voiceListBean : voiceDetail.first) {
            if (TextUtils.isEmpty(voiceListBean.getVoiceUrl())) {
                continue;
            }
            if (voiceListBean.getId() == id) {
                scrollToBean.setValue(voiceListBean);
                setChoiceVoiceBean(voiceListBean, true);
                notifyBean.setValue(voiceListBean);
                break;
            }
        }
    }


    private void requestVoiceTypeList() {
        voiceAIRepository.requestVoiceType().subscribe(new SingleObserver<VoiceTypeResponse>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                addDisposable(d);
            }

            @Override
            public void onSuccess(@NonNull VoiceTypeResponse voiceTypeResponse) {
                voiceTypeList.setValue(voiceTypeResponse.getTypeList());
            }

            @Override
            public void onError(@NonNull Throwable e) {
                ErrorHelper.errorThrowableToast(e, ToastUtil.LENGTH_SHORT);
            }
        });
    }

    public void setLastVoiceGenerateTxt(String generateTxt) {
        KVUtils.getDefault().putString(LAST_GENERATE_TEXT, generateTxt);
    }


    public void refreshVoiceList(String id) {
        refreshVoiceList(id, null);
    }

    public void refreshVoiceList(String id, VoiceListBean bean) {
        if (Objects.equals(this.currentTypeId, id)) {
            return;
        }
        this.currentTypeId = id;
        requestVoiceList(currentTypeId, bean);
    }

    private void requestVoiceList(String id, VoiceListBean bean) {
        if (voiceListDisposable != null && !voiceListDisposable.isDisposed()) {
            voiceListDisposable.dispose();
        }
        voiceAIRepository.requestVoiceList(id).subscribe(new SingleObserver<VoiceListResponse>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                voiceListDisposable = d;
                addDisposable(d);
            }

            @Override
            public void onSuccess(@NonNull VoiceListResponse voiceListResponse) {
                showQueryLoading.setValue(false);
                List<VoiceListBean> voiceList = voiceListResponse.getVoiceList();
                if (voiceList == null) {
                    voiceList = new ArrayList<>();
                }
                if (voiceListResponse.isShowAdd()) {
                    VoiceListBean voiceListBean = new VoiceListBean();
                    voiceListBean.setAddIcon(true);
                    voiceListBean.setId(-1);
                    voiceListBean.setName(ContextUtil.getContext().getString(R.string.add_voice));
                    voiceList.add(0, voiceListBean);
                }
                if (bean != null) {
                    voiceDetailList.setValue(new Pair<>(voiceList, bean));
                } else {
                    for (VoiceListBean voiceListBean : voiceList) {
                        if (voiceListBean.isAddIcon()) {
                            continue;
                        }
                        setChoiceVoiceBean(voiceListBean, false);
                        break;
                    }
                    voiceDetailList.setValue(new Pair<>(voiceList, null));
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
                showQueryLoading.setValue(false);
                ErrorHelper.errorThrowableToast(e, ToastUtil.LENGTH_SHORT);
            }
        });
    }


    private void setChoiceVoiceBean(VoiceListBean voiceListBean, boolean playVoice) {
        if (this.choiceVoiceBean != null) {
            this.choiceVoiceBean.setCheck(false);
            this.choiceVoiceBean.setVoicePlayState(VoiceListBean.VoicePlayState.INITIAL);
        }
        this.choiceVoiceBean = voiceListBean;
        this.choiceVoiceBean.setCheck(true);
        if (playVoice) {
            Bundle bundle = new Bundle();
            bundle.putString(EventId.ID, String.valueOf(voiceListBean.getId()));
            EventHandler.report(EventId.homelistclick_001, bundle);
            playExampleVoice.setValue(choiceVoiceBean);
        }
    }

    public void voiceItemClick(VoiceListBean voiceListBean) {
        setChoiceVoiceBean(voiceListBean, true);
    }

    public void seeAdGenerate() {
        if (choiceVoiceBean == null) {
            ToastUtil.show(R.string.voice_ai_no_choice, ToastUtil.LENGTH_SHORT);
            return;
        }
        requestGenerateVoice();
    }

    public void setVoicePlayEnd() {
        if (choiceVoiceBean != null) {
            choiceVoiceBean.setVoicePlayState(VoiceListBean.VoicePlayState.INITIAL);
        }
    }

    public void onSettingClick() {
        SettingActivity.start(ActivityUtil.getTopActivity());
    }


    public void onGoSubscriptionClick() {
        EventHandler.report(EventId.homeprobutton_001);
        SubscriptionPageActivity.start(ActivityUtil.getTopActivity());
    }

    public void onGetMoreClick() {
        EventHandler.report(EventId.homegetmore_001);
        SubscriptionPageActivity.start(ActivityUtil.getTopActivity());
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (recommendObserver != null) {
            voiceAIRepository.getRecommendClickBean().removeObserver(recommendObserver);
        }
        if (cloneObserver != null) {
            voiceAIRepository.getCloneExecuteSuccess().removeObserver(cloneObserver);
        }
        if (useCloneObserver != null) {
            voiceAIRepository.getUseClonedVoiceEvent().removeObserver(useCloneObserver);
        }
    }


}
