package com.uiui.zyappstore.service.main;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.task.DownloadTask;
import com.blankj.utilcode.util.NetworkUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.trello.rxlifecycle4.LifecycleProvider;
import com.trello.rxlifecycle4.LifecycleTransformer;
import com.trello.rxlifecycle4.RxLifecycle;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.trello.rxlifecycle4.android.RxLifecycleAndroid;
import com.uiui.zyappstore.bean.BaseResponse;
import com.uiui.zyappstore.network.HTTPInterface;
import com.uiui.zyappstore.network.NetInterfaceManager;
import com.uiui.zyappstore.utils.ApkUtils;
import com.uiui.zyappstore.utils.JGYUtils;
import com.uiui.zyappstore.utils.LogUtils;
import com.uiui.zyappstore.utils.SPUtils;
import com.uiui.zyappstore.utils.Utils;

import org.jetbrains.annotations.NotNull;

import java.io.File;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import io.reactivex.rxjava3.subjects.BehaviorSubject;

public class MainService extends Service implements MainSContact.MainView, NetworkUtils.OnNetworkStatusChangedListener, LifecycleProvider<ActivityEvent> {
    private static final String TAG = MainService.class.getSimpleName();

    public MainSPresenter mPresenter;

    private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create();

    @Override
    public void onDisconnected() {
        Log.e(TAG, "网络未连接");
    }

    @Override
    public void onConnected(NetworkUtils.NetworkType networkType) {
        Log.e(TAG, "网络已连接");
        if (JGYUtils.getInstance().isScreenOn()) {
            HTTPInterface.checkUpdate(MainService.this);
            HTTPInterface.checkUpdate(MainService.this, "com.uiui.sn");
            mPresenter.getSnTag();
        }
    }

    @NotNull
    @Override
    public Observable<ActivityEvent> lifecycle() {
        return lifecycleSubject.hide();
    }

    @NotNull
    @Override
    public <T> LifecycleTransformer<T> bindUntilEvent(@NotNull ActivityEvent event) {
        return RxLifecycle.bindUntilEvent(lifecycleSubject, event);
    }

    @NotNull
    @Override
    public <T> LifecycleTransformer<T> bindToLifecycle() {
        return RxLifecycleAndroid.bindActivity(lifecycleSubject);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Aria.download(this).register();
//        return START_STICKY;
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "onCreate: ");

        Aria.download(this).register();

        HTTPInterface.checkUpdate(MainService.this);

        lifecycleSubject.onNext(ActivityEvent.CREATE);
        mPresenter = new MainSPresenter(this);
        mPresenter.setLifecycle(lifecycleSubject);
        mPresenter.attachView(this);
        NetworkUtils.registerNetworkStatusChangedListener(this);

        File file = new File(JGYUtils.getInstance().getDownLoadPath());
        if (file.isFile() || !file.exists()) {
            file.delete();
            file.mkdirs();
        }
        mPresenter.getSnTag();
        JGYUtils.getInstance().checkLocalExternalFiles();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        lifecycleSubject.onNext(ActivityEvent.DESTROY);
        NetworkUtils.unregisterNetworkStatusChangedListener(this);
        mPresenter.detachView();
    }

    @Override
    public void setSnTag() {

    }

    //在这里处理任务执行中的状态，如进度进度条的刷新
    @Download.onTaskRunning
    void running(DownloadTask task) {
        LogUtils.e(TAG, "running: " + "getState = " + task.getState() + "getPercent = " + task.getPercent() + "getExtendField = " + task.getExtendField());
    }

    @Download.onTaskComplete
    void taskComplete(DownloadTask task) {
        Log.e(TAG, "taskComplete: " );
        //在这里处理任务完成的状态
        final String downloadPath = task.getFilePath();
        if (null != task.getExtendField()) {
            JsonObject jsonObject = JsonParser.parseString(task.getExtendField()).getAsJsonObject();
            String packageName = jsonObject.get("app_package").getAsString();
            File file = new File(downloadPath);
            int admin_id = (int) SPUtils.get(MainService.this, "admin_id", -1);
            NetInterfaceManager.getInstance()
                    .getDownloadAppControl()
                    .sendDownloadApp(packageName, file.length(), Utils.getSerial(), admin_id)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<BaseResponse>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NonNull BaseResponse baseResponse) {
                            int code = baseResponse.code;
                            String msg = baseResponse.msg;
                            Log.e("taskComplete", "onNext: " + "code" + code + ",msg:" + msg);

                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            Log.e("taskComplete", "onError: " + e.getMessage());
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
        ApkUtils.installApp(MainService.this, task.getFilePath());
    }

    @Download.onTaskFail
    void taskFail(DownloadTask task, Exception e) {
        Log.e(TAG, "taskFail: ");
        Aria.download(this).resumeAllTask();
        try {
            final String filepath = task.getFilePath();
            final String packageName = task.getExtendField();
            Log.e(TAG, "taskFail: " + packageName + "  filepath： " + filepath);
            Aria.download(this).load(task.getDownloadEntity().getId()).cancel(true);
        } catch (Exception ex) {
            Log.e(TAG, "taskFail: " + "Exception: " + ex.getLocalizedMessage());
        }
    }
}
