package com.sheep.jiuyan.samllsheep.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;

import com.sheep.gamegroup.greendao.DDProviderHelper;
import com.sheep.gamegroup.greendao.download.ProcessRecord;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.LogUtil;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import rx.functions.Action1;

/**
 * Created by realicing on 2018/5/8.
 * realicing@sina.com
 * 应用自动审核任务监听应用使用时长----5.0以下使用该方案；5.0以上在app内直接读取应用使用情况
 */
public class AutoCheckService extends Service {
    private void stopTimer() {
        if (subscription != null && !subscription.isDisposed()) {
            subscription.dispose();
        }
        subscription = null;
    }

    private Disposable subscription;

    private void startTimer() {
        if (subscription == null)
            subscription = Observable.interval(1_000L, TimeUnit.MILLISECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long count) {
                            LogUtil.println("AutoCheckService", "count", "=", count);
                            if(TextUtils.isEmpty(userId)){//没有登录不统计
                                return;
                            }
                            String packageName = ListenerShotService.getProcessPackageNameInForeground(getApplicationContext());
                            if(TextUtils.equals(lastPackageName, packageName) && !TextUtils.isEmpty(packageName) && !ListUtil.isEmpty(taskList) && taskList.contains(packageName)) {
                                final ProcessRecord processRecord = new ProcessRecord();
                                processRecord.setPackageName(packageName);
                                processRecord.setUserId(userId);
                                DDProviderHelper.getInstance().addOrUpdateProcessRecord(processRecord, new Action1<ProcessRecord>() {
                                    @Override
                                    public void call(ProcessRecord lastProcessRecord) {
                                        if(lastProcessRecord == null){
                                            processRecord.setRunTime(1);
                                        } else {
                                            processRecord.setRunTime(lastProcessRecord.getRunTime() + 1);
                                        }
                                    }
                                });
                            }
                            lastPackageName = packageName;
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) {
                            LogUtil.println("AutoCheckService", "Throwable", "=", throwable.getMessage());
                        }
                    });
    }
    //上一次获取到的包名
    private String lastPackageName;


    //不与Activity进行绑定.
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        startTimer();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        stopTimer();
    }


    //需要监听的
    private List<String> taskList;
    public static final String EXTRA_KEY_TASK_LIST = "task_list";
    public static final String EXTRA_KEY_USER_ID = "user_id";
    //是否采用该方案
    public static final boolean IS_USE_THIS_SERVICE = /*BuildConfig.DEBUG || */android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP;
    //登录的用户id
    private String userId;
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            taskList = intent.getStringArrayListExtra(EXTRA_KEY_TASK_LIST);
            userId = intent.getStringExtra(EXTRA_KEY_USER_ID);
        }
        return super.onStartCommand(intent, flags, startId);
    }

}
