package com.virjar.g4proxy.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.virjar.g4proxy.Constant;
import com.virjar.g4proxy.utils.DeviceMessageUtil;
import com.virjar.g4proxy.utils.HttpClientUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;
import top.wuhaojie.installerlibrary.AutoInstaller;

public class SchedulerTaskService extends Service {

    //查询更新的间隔 （单位：分钟）
    public static final int updateInterval = 10;


    public static final String getNewestModifiedApkUrl = "http://www.scumall.com:5597/hermes/ModifiedApp/getNewestModifiedApk?appPackageName=";

    private long lastCheckUpdateTimestamp = 0;


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

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


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        checkAndRunTask();
        return START_STICKY;
    }


    private void checkAndRunTask() {
        if (System.currentTimeMillis() - lastCheckUpdateTimestamp < (updateInterval * 1000 * 60) / 3) {
            return;
        }
        lastCheckUpdateTimestamp = System.currentTimeMillis();


        runAppInstallTask();

        runUploadMessageTask();
    }


    private void runUploadMessageTask() {
        JSONObject deviceMessage = DeviceMessageUtil.getDeviceMessage(this);

    }


    private void runAppInstallTask() {
        final String packageName = getApplicationInfo().packageName;
        Request request = HttpClientUtils.getRequest(getNewestModifiedApkUrl + packageName);

        HttpClientUtils.getClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@javax.annotation.Nullable Call call, @javax.annotation.Nullable IOException e) {
                Log.e(Constant.TAG, "get downloadUrl failed", e);
            }

            @Override
            public void onResponse(@javax.annotation.Nullable Call call, @javax.annotation.Nullable Response response) {
                try {
                    handleResponse(response, packageName);
                } catch (JSONException | PackageManager.NameNotFoundException | IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void doInstall(final String url) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Log.e(Constant.TAG, "installing");
                AutoInstaller installer = AutoInstaller.getDefault(SchedulerTaskService.this);
                installer.installFromUrl(url);
                installer.setOnStateChangedListener(new AutoInstaller.OnStateChangedListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onComplete() {

                    }

                    @Override
                    public void onNeed2OpenService() {
                        Toast.makeText(SchedulerTaskService.this, "请打开辅助功能服务", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void needPermission() {
                        Toast.makeText(SchedulerTaskService.this, "需要申请存储空间权限", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    public void handleResponse(Response response, String packageName) throws JSONException, PackageManager.NameNotFoundException, IOException {

        if (response.body() == null) {
            return;
        }
        String responseJson = response.body().string();

        Log.i(Constant.TAG, "app update config service response: " + responseJson);
        JSONObject jsonObject = new JSONObject(responseJson);
        jsonObject = jsonObject.optJSONObject("data");
        String downloadUrl = jsonObject.optString("downloadUrl");
        long versionCode = jsonObject.optLong("versionCode");

        Log.i(Constant.TAG, "downloadUrl: " + downloadUrl);
        Log.i(Constant.TAG, "up-to-date versionCode: " + versionCode);
        PackageInfo packageInfo = getPackageManager().getPackageInfo(packageName, PackageManager.GET_META_DATA);
        if (packageInfo.versionCode < versionCode) {
            Log.i(Constant.TAG, "the app need update,with download url: " + downloadUrl);
            doInstall(downloadUrl);
        }
    }

    private void registerAlarm() {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        int time = 1000 * 60 * updateInterval;
        //获取系统开机至今所经历的毫秒
        long startTime = SystemClock.elapsedRealtime() + time;
        Intent intent = new Intent(this, SchedulerTaskService.class);
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
        if (alarmManager == null) {
            return;
        }
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, startTime, pendingIntent);
    }

}
