package com.atmob.voiceai.data.repositories;


import android.util.Pair;

import androidx.annotation.IntDef;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.atmob.app.lib.handler.RxHttpHandler;
import com.atmob.app.lib.livedata.SingleLiveEvent;
import com.atmob.common.runtime.ContextUtil;
import com.atmob.voiceai.R;
import com.atmob.voiceai.data.api.AtmobApi;
import com.atmob.voiceai.data.api.GenerateApi;
import com.atmob.voiceai.data.api.bean.UserVoiceBean;
import com.atmob.voiceai.data.api.bean.VoiceListBean;
import com.atmob.voiceai.data.api.request.BaseRequest;
import com.atmob.voiceai.data.api.request.TextTosSpeechRequest;
import com.atmob.voiceai.data.api.request.VoiceListRequest;
import com.atmob.voiceai.data.api.response.TextToSpeechResponse;
import com.atmob.voiceai.data.api.response.VoiceInfoResponse;
import com.atmob.voiceai.data.api.response.VoiceListResponse;
import com.atmob.voiceai.data.api.response.VoiceTypeResponse;
import com.atmob.voiceai.utils.BoxingUtil;
import com.atmob.voiceai.utils.ThreePair;
import com.atmob.voiceai.utils.ToastUtil;

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

import javax.inject.Inject;
import javax.inject.Singleton;

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;

@Singleton
public class VoiceAIRepository {


    private final AtmobApi atmobApi;
    private final GenerateApi generateApi;
    private final HistoryRepository historyRepository;
    private final MemberRepository memberRepository;

    private final SingleLiveEvent<?> cloneExecuteSuccess = new SingleLiveEvent<>();
    private boolean textToSpeechRequest;
    private final MutableLiveData<Integer> adFreeGenerateNumber = new MutableLiveData<>();

    private VoiceListBean requestCloneBean;
    private String textToSpeechTxt;

    private final MutableLiveData<ThreePair<Integer, String, UserVoiceBean>> textToSpeechState = new MutableLiveData<>();

    private final SingleLiveEvent<VoiceListBean> recommendClickBean = new SingleLiveEvent<>();
    private final SingleLiveEvent<Integer> useClonedVoiceEvent = new SingleLiveEvent<>();

    private boolean isRequestFreeGenerate;


    @IntDef({TextToSpeechState.GENERATING, TextToSpeechState.GENERATED, TextToSpeechState.ERROR})
    public @interface TextToSpeechState {
        int GENERATING = 1;
        int GENERATED = 2;
        int ERROR = 3;
    }

    @Inject
    public VoiceAIRepository(AtmobApi atmobApi, GenerateApi generateApi, MemberRepository memberRepository, HistoryRepository historyRepository) {
        this.atmobApi = atmobApi;
        this.generateApi = generateApi;
        this.memberRepository = memberRepository;
        this.historyRepository = historyRepository;
        refreshVoiceInfo();
    }

    public void setUseClonedVoiceEvent(int id) {
        useClonedVoiceEvent.setValue(id);
    }

    public LiveData<Integer> getUseClonedVoiceEvent() {
        return useClonedVoiceEvent;
    }

    public LiveData<?> getCloneExecuteSuccess() {
        return cloneExecuteSuccess;
    }

    public void setCloneExecuteSuccessEvent() {
        cloneExecuteSuccess.call();
    }

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

    public void setRecommendClickBean(VoiceListBean bean) {
        recommendClickBean.setValue(bean);
    }

    public LiveData<VoiceListBean> getRecommendClickBean() {
        return recommendClickBean;
    }

    public VoiceListBean getRequestCloneBean() {
        return requestCloneBean;
    }

    public String getTextToSpeechTxt() {
        return textToSpeechTxt;
    }

    public LiveData<ThreePair<Integer, String, UserVoiceBean>> getTextToSpeechState() {
        return textToSpeechState;
    }


    private void refreshVoiceInfo() {
        if (isRequestFreeGenerate || BoxingUtil.boxing(memberRepository.getIsMember().getValue())) {
            return;
        }
        requestVoiceInfo().subscribe(new SingleObserver<VoiceInfoResponse>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                isRequestFreeGenerate = true;
            }

            @Override
            public void onSuccess(@NonNull VoiceInfoResponse voiceInfoResponse) {
                isRequestFreeGenerate = false;
                adFreeGenerateNumber.setValue(voiceInfoResponse.getVoiceTimes());
            }

            @Override
            public void onError(@NonNull Throwable e) {
                e.printStackTrace();
                isRequestFreeGenerate = false;
            }
        });
    }

    private Single<VoiceInfoResponse> requestVoiceInfo() {
        return atmobApi.getVoiceInfo(new BaseRequest())
                .compose(RxHttpHandler.handle(true))
                .compose(RxJavaUtil.SingleSchedule.io2Main());
    }

    public Single<VoiceTypeResponse> requestVoiceType() {
        return atmobApi.getVoiceType(new BaseRequest())
                .compose(RxHttpHandler.handle(false))
                .compose(RxJavaUtil.SingleSchedule.io2Main());
    }

    public Single<VoiceListResponse> requestVoiceList(String id) {
        return atmobApi.getVoiceList(new VoiceListRequest(id))
                .compose(RxHttpHandler.handle(true))
                .compose(RxJavaUtil.SingleSchedule.io2Main());
    }


    public void requestTextToSpeech(VoiceListBean bean, String content) {
        if (bean == null || textToSpeechRequest) {
            return;
        }
        requestCloneBean = bean;
        textToSpeechTxt = content;
//        /********仅测试使用******/
//        UserVoiceBean userVoiceBean = new UserVoiceBean();
//        userVoiceBean.setVoiceAvatar(bean.getAvatarUrl());
//        userVoiceBean.setVoiceId(bean.getId());
//        userVoiceBean.setVoiceName(bean.getName());
//        userVoiceBean.setContent(content);
//        userVoiceBean.setVoiceUrl("http://cdn.atmob.com/upload/project_voice/text_to_speech/20240510/986334800900366336.mp3");
//        textToSpeechState.setValue(new ThreePair<>(TextToSpeechState.GENERATED, null, userVoiceBean));
//        /********仅测试使用******/
        textToSpeech(bean.getId(), bean.getVoiceType(), content).subscribe(new SingleObserver<TextToSpeechResponse>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                textToSpeechRequest = true;
                textToSpeechState.setValue(new ThreePair<>(TextToSpeechState.GENERATING, null, null));
            }

            @Override
            public void onSuccess(@NonNull TextToSpeechResponse textToSpeechResponse) {
                textToSpeechRequest = false;
                textToSpeechState.setValue(new ThreePair<>(TextToSpeechState.GENERATED, null, textToSpeechResponse.getUserVoice()));
            }

            @Override
            public void onError(@NonNull Throwable throwable) {
                textToSpeechRequest = false;
                if (throwable instanceof RxHttpHandler.ServerErrorException) {
                    RxHttpHandler.ServerErrorException serverErrorException = (RxHttpHandler.ServerErrorException) throwable;
                    textToSpeechState.setValue(new ThreePair<>(TextToSpeechState.ERROR, serverErrorException.getMsg(), null));
                } else {
                    textToSpeechState.setValue(new ThreePair<>(TextToSpeechState.ERROR, ContextUtil.getContext().getString(R.string.generate_error), null));
                }
            }
        });
    }

    private Single<TextToSpeechResponse> textToSpeech(int id, int voiceType, String content) {
        return generateApi.textToSpeech(new TextTosSpeechRequest(id, voiceType, content))
                .compose(RxHttpHandler.handle(true))
                .compose(RxJavaUtil.SingleSchedule.io2Main())
                .doOnSuccess(data -> {
                    refreshVoiceInfo();
                    historyRepository.refreshCloneHistory(1);
                });
    }


}
