package com.example.audiovisualrecord.ui.main;

import android.os.Environment;
import android.util.Log;

import com.arthenica.mobileffmpeg.Config;
import com.arthenica.mobileffmpeg.FFmpeg;
import com.arthenica.mobileffmpeg.FFprobe;
import com.example.audiovisualrecord.R;

import com.example.audiovisualrecord.utils.api.ApiService;
import com.example.audiovisualrecord.utils.api.HttpMethods;
import com.example.audiovisualrecord.utils.api.apidata.searchco.CORequest;
import com.example.audiovisualrecord.utils.api.apidata.searchco.COResultList;
import com.example.audiovisualrecord.utils.api.apidata.logoutsid.LogoutSidResponse;
import com.example.audiovisualrecord.utils.api.apidata.searchsid.SIDDataList;
import com.example.audiovisualrecord.utils.api.apidata.searchtype.TYPERequest;
import com.example.audiovisualrecord.utils.api.apidata.searchtype.TYPEResultList;
import com.example.audiovisualrecord.utils.api.searchshift.SHIFTRequest;
import com.example.audiovisualrecord.utils.api.searchshift.SHIFTResultList;
import com.example.audiovisualrecord.utils.api.searchpz.PZRequest;
import com.example.audiovisualrecord.utils.api.searchpz.PZResultList;
import com.example.audiovisualrecord.utils.api.searchdp.DPRequest;
import com.example.audiovisualrecord.utils.api.searchdp.DPResultList;
import com.example.audiovisualrecord.utils.rxjava.SchedulerProviderImp;

import java.io.File;
import java.util.ArrayList;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;

import static com.arthenica.mobileffmpeg.Config.RETURN_CODE_CANCEL;
import static com.arthenica.mobileffmpeg.Config.RETURN_CODE_SUCCESS;

public class MainPresenter<V extends MainContract.View> implements MainContract.Presenter<V> {

    //    private String KEY_SEARCH_CO = "6c66fcbd-6dfe-45a2-ad6b-cbcda09b25bd";
    private String KEY_SEARCH_CO = "3b0f7c72-5479-46c1-b26d-224748e64d7a";
    private String KEY_SEARCH_PZ = "78bc27f8-6c1b-4172-ba61-05798001671b";
    private String KEY_SEARCH_DP = "1c76477f-1fb0-49fb-a5bd-e75311bbe691";
    private String KEY_SEARCH_SHIFT = "3e161e49-30d5-44ce-bbc4-3bcff49f7c37";
    private String KEY_SEARCH_TYPE = "145ce81d-7bae-4848-a38a-e0e738385681";
    private String USER_ID = "N000158385";

    private V view;
    private String LOGIN_AUTHORIZED_ID = "acd9be92-46bf-4185-8721-5b60c67f0742";
    private ApiService api;
    SchedulerProviderImp schedulerProviderImp = new SchedulerProviderImp();
    private CompositeDisposable compositeDisposable;

    public MainPresenter(V view) {
        this.view = view;
        api = HttpMethods.getInstance().getApi();
        compositeDisposable = new CompositeDisposable();

    }

    @Override
    public void onGetComData() {
        String url = view.getResourceString(R.string.api_on_getCO);
        final CORequest mCORequest = new CORequest(KEY_SEARCH_CO, USER_ID);
        compositeDisposable.add(api.getCO(url, mCORequest)
                .subscribeOn(schedulerProviderImp.io())
                .observeOn(schedulerProviderImp.ui())
                .subscribeWith(new DisposableObserver<COResultList>() {

                    @Override
                    public void onNext(COResultList mCOResultList) {
                        view.setCOData(mCOResultList.getcOResponseList());
                    }

                    @Override
                    public void onError(Throwable e) {
                        view.showDialogCaveatMessage(view.getResourceString(R.string.add_device_error));

                    }

                    @Override
                    public void onComplete() {

                    }
                })
        );
    }

    @Override
    public void onGetPZData() {
        String url = view.getResourceString(R.string.api_on_getMNTFCT);
        PZRequest mPZRequest = new PZRequest(KEY_SEARCH_PZ, USER_ID);
        compositeDisposable.add(api.getPZ(url, mPZRequest)
                .subscribeOn(schedulerProviderImp.io())
                .observeOn(schedulerProviderImp.ui())
                .subscribeWith(new DisposableObserver<PZResultList>() {

                    @Override
                    public void onNext(PZResultList mPZResultList) {
                        view.setPZData(mPZResultList.getmNTFCTResponse());
                    }

                    @Override
                    public void onError(Throwable e) {
                        view.showDialogCaveatMessage(view.getResourceString(R.string.add_device_error));

                    }

                    @Override
                    public void onComplete() {

                    }
                })
        );
    }

    @Override
    public void onGetDPData(String CO, String PZ) {
        final DPRequest mDPRequest = new DPRequest(KEY_SEARCH_DP, USER_ID, CO, PZ);
        String url = view.getResourceString(R.string.api_on_getDP);
        compositeDisposable.add(api.getDP(url, mDPRequest)
                .subscribeOn(schedulerProviderImp.io())
                .observeOn(schedulerProviderImp.ui())
                .subscribeWith(new DisposableObserver<DPResultList>() {

                    @Override
                    public void onNext(DPResultList mDPResultList) {
                        if (mDPResultList.getmDPResponseList().size() < 1) {
                            view.showDialogCaveatMessage(view.getResourceString(R.string.get_pmfct_error_no_data));
                        } else {
                            view.setDPNMData(mDPResultList.getmDPResponseList());
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        view.showDialogCaveatMessage(view.getResourceString(R.string.add_device_error));

                    }

                    @Override
                    public void onComplete() {

                    }
                })
        );
    }

    @Override
    public void onGetSHIFTData(String CO, String PMFCT) {
        SHIFTRequest mSHIFTRequest = new SHIFTRequest(KEY_SEARCH_SHIFT, USER_ID, CO, PMFCT);
        String url = view.getResourceString(R.string.api_on_getSHIFT);
        compositeDisposable.add(api.getSHIFT(url, mSHIFTRequest)
                .subscribeOn(schedulerProviderImp.io())
                .observeOn(schedulerProviderImp.ui())
                .subscribeWith(new DisposableObserver<SHIFTResultList>() {

                    @Override
                    public void onNext(SHIFTResultList mSHIFTResultList) {
                        if (mSHIFTResultList.getmSHIFTResponseList().size() < 1) {
                            view.showDialogCaveatMessage(view.getResourceString(R.string.get_shift_error_no_data));
                        } else {
                            view.setEQKDData(mSHIFTResultList.getmSHIFTResponseList());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        view.showDialogCaveatMessage(view.getResourceString(R.string.add_device_error));

                    }

                    @Override
                    public void onComplete() {

                    }
                })
        );
    }

    @Override
    public void onGetTYPEData(String CO, String PMFCT) {
        final TYPERequest mTypeRequest = new TYPERequest(KEY_SEARCH_TYPE, USER_ID, CO, PMFCT);
        String url = view.getResourceString(R.string.api_on_getTYPE);
        compositeDisposable.add(api.getTYPE(url, mTypeRequest)
                .subscribeOn(schedulerProviderImp.io())
                .observeOn(schedulerProviderImp.ui())
                .subscribeWith(new DisposableObserver<TYPEResultList>() {
                    @Override
                    public void onNext(TYPEResultList mTYPEResultList) {
                        if (mTYPEResultList.getmTYPEResponseList().size() < 1) {
                            view.showDialogCaveatMessage(view.getResourceString(R.string.get_type_error_no_data));
                        } else {
                            view.setTYPEData(mTYPEResultList.getmTYPEResponseList());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        view.showDialogCaveatMessage("請重試或檢查網路狀態");
                    }

                    @Override
                    public void onComplete() {

                    }
                })
        );
    }

    @Override
    public void onGetSid(final ArrayList<String> uriList, final String type) {
        String url = view.getResourceString(R.string.api_on_getSID);
        compositeDisposable.add(api.getSID(url)
                .subscribeOn(schedulerProviderImp.io())
                .observeOn(schedulerProviderImp.ui())
                .subscribeWith(new DisposableObserver<SIDDataList>() {
                    @Override
                    public void onNext(SIDDataList mSIDDataList) {
                        view.onUploadFile(uriList,type,mSIDDataList.getsIdDataList().getSid());
//                        Log.e("sss", mSIDDataList.getSuccess());
                    }

                    @Override
                    public void onError(Throwable e) {
                        view.showDialogCaveatMessage("請重試或檢查網路狀態");
                        Log.e("error", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                    }
                })
        );
    }

    @Override
    public void onLogoutSid(String sid) {
        String url = "https://webapp.fpcitc.com.tw/SOP/api/FileUpload/PostLogout?sid=" + sid;
        compositeDisposable.add(api.onLogoutSid(url)
                .subscribeOn(schedulerProviderImp.io())
                .observeOn(schedulerProviderImp.ui())
                .subscribeWith(new DisposableObserver<LogoutSidResponse>() {
                    @Override
                    public void onNext(LogoutSidResponse mLogoutSidResponse) {
                        Log.e("success", mLogoutSidResponse.getSuccess());
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e.getMessage().contains("No address associated with hostname")) {
                            view.showDialogCaveatMessage("請檢查網路狀態");
                        }
                    }

                    @Override
                    public void onComplete() {
                    }
                }));

    }

    @Override
    public void segVideo(final String path, final String name) {
        view.showProgressDialog("影片分割中");
        view.showProgressDialog("影片分割中");
        view.showProgressDialog("影片分割中");
        view.showProgressDialog("影片分割中");
        view.showProgressDialog("影片分割中");
        view.showProgressDialog("影片分割中");
        view.showProgressDialog("影片分割中");
        view.showProgressDialog("影片分割中");
        view.showProgressDialog("影片分割中");

        final ArrayList<String> segVideoList = new ArrayList<>();

        new Thread(new Runnable() {
            @Override
            public void run() {
                File video = new File(path);
                int sizeLimit = 50 * 1024 * 1024;
                Log.e("size", video.length() + "");
                int duration = (int) (FFprobe.getMediaInformation(path).getDuration() / 1000); //影片秒數
                int startTime = 0;
                int segTime = 30;   //分割秒數
                int loop = 0;
                if (duration % segTime != 0) {
                    loop = duration / segTime + 1;
                } else {
                    loop = duration / segTime;
                }
                if (video.length() > sizeLimit) {
                    for (int i = 0; i < loop; i++) {

                        int rc = FFmpeg.execute("-ss " + startTime + " -i " + path + " -t " + segTime + " " + Environment.getExternalStorageDirectory().toString() + "/seg_" + i +"_"+ video.getName().replace(".mp4", "") +".mp4");
                        segVideoList.add(Environment.getExternalStorageDirectory().toString() + "/seg_" + i +"_"+ video.getName());


                        if (rc == RETURN_CODE_SUCCESS) {
                            Log.i(Config.TAG, "Command execution completed successfully.");
                        } else if (rc == RETURN_CODE_CANCEL) {
                            Log.i(Config.TAG, "Command execution cancelled by user.");
                        } else {

                            Log.i(Config.TAG, String.format("Command execution failed with rc=%d and the output below.", rc));
                            Config.printLastCommandOutput(Log.INFO);
                        }
                        startTime += segTime;
                    }
                    view.dismissProgressDialog();
                    onGetSid(segVideoList, "video");
                } else {
                    //沒超過
                    segVideoList.add(path);
                    view.dismissProgressDialog();
                    onGetSid(segVideoList, "video");
                }
            }
        }).start();
    }

    @Override
    public String onJudgmentPath(String pathCompany, String pathFactoryArea, String pathFactoryClass, String pathClass, String pathShootType) {
        String path = "";
        if ("仁武氯乙烯廠製造一課".equals(pathFactoryClass) && "SOP導讀".equals(pathShootType)) {
            path = "/仁武氯乙烯廠製造一課/1_SOP導讀";
        } else if ("仁武氯乙烯廠製造一課".equals(pathFactoryClass) && "SOP審視會議".equals(pathShootType)) {
            path = "/仁武氯乙烯廠製造一課/2_SOP審視修訂";
        } else if ("仁武氯乙烯廠製造一課".equals(pathFactoryClass) && "落實度查核".equals(pathShootType) && "DA".equals(pathClass)) {
            path = "/仁武氯乙烯廠製造一課/3_SOP落實度查核/DA";
        } else if ("仁武氯乙烯廠製造一課".equals(pathFactoryClass) && "落實度查核".equals(pathShootType) && "DB".equals(pathClass)) {
            path = "/仁武氯乙烯廠製造一課/3_SOP落實度查核/DB";
        } else if ("仁武氯乙烯廠製造一課".equals(pathFactoryClass) && "落實度查核".equals(pathShootType) && "DC".equals(pathClass)) {
            path = "/仁武氯乙烯廠製造一課/3_SOP落實度查核/DC";
        } else if ("仁武氯乙烯廠製造一課".equals(pathFactoryClass) && "落實度查核".equals(pathShootType) && "DD".equals(pathClass)) {
            path = "/仁武氯乙烯廠製造一課/3_SOP落實度查核/DD";
        }
        return path;
    }

}
