package com.uiui.zyappstore.service;

/**
 * 作者 mjsheng
 * 日期 2019/4/1 10:58
 * 邮箱 501802639@qq.com
 * 来自：
 */

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.task.DownloadTask;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.uiui.zyappstore.KeepAliveConnection;
import com.uiui.zyappstore.bean.BaseResponse;
import com.uiui.zyappstore.network.NetInterfaceManager;
import com.uiui.zyappstore.receiver.NewAppReceiver;
import com.uiui.zyappstore.utils.ApkUtils;
import com.uiui.zyappstore.utils.LogUtils;
import com.uiui.zyappstore.utils.SPUtils;
import com.uiui.zyappstore.utils.ServiceAliveUtils;
import com.uiui.zyappstore.utils.Utils;

import java.io.File;

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


/**
 * 守护进程 双进程通讯
 *
 * @author LiGuangMin
 * @time Created by 2018/8/17 11:27
 */
public class GuardService extends Service {
    private final static String TAG = GuardService.class.getSimpleName();
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            LogUtils.e(TAG, "GuardService:建立链接");
            boolean isServiceRunning = ServiceAliveUtils.isServiceAlice(GuardService.this);
            if (!isServiceRunning) {
                Intent i = new Intent(GuardService.this, DownloadService.class);
                startService(i);
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            // 断开链接
            startService(new Intent(GuardService.this, StepService.class));
            // 重新绑定
            bindService(new Intent(GuardService.this, StepService.class), mServiceConnection, Context.BIND_IMPORTANT);
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new KeepAliveConnection.Stub() {
        };
    }

    @Override
    public void onCreate() {
        super.onCreate();
        registerNewAppReceiver();
    }

    private NewAppReceiver mNewAppReceiver;

    private void registerNewAppReceiver() {
        if (mNewAppReceiver == null) {
            mNewAppReceiver = new NewAppReceiver();
            IntentFilter filter = new IntentFilter();
            filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
            filter.addAction(Intent.ACTION_PACKAGE_ADDED);
            filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
            filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
            filter.addDataScheme("package");
            registerReceiver(mNewAppReceiver, filter);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mNewAppReceiver != null) {
            unregisterReceiver(mNewAppReceiver);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Aria.init(this);
        Aria.get(this).getDownloadConfig().setMaxTaskNum(1);
        Aria.download(this).register();
        bindService(new Intent(this, StepService.class), mServiceConnection, Context.BIND_IMPORTANT);
        return START_STICKY;
    }


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

    @Download.onTaskComplete
    void taskComplete(DownloadTask task) {
        //在这里处理任务完成的状态
        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(GuardService.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() {

                        }
                    });
        }

        new Thread(() -> ApkUtils.installApp(GuardService.this, downloadPath)).start();
    }
}

