package com.maniu.mn_vip_jetpack_other;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.work.Constraints;
import androidx.work.Data;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;

import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.maniu.mn_vip_jetpack_other.workmanager.MyWorkManager;
import com.maniu.mn_vip_jetpack_other.workmanager.MyWorkManager2;
import com.maniu.mn_vip_jetpack_other.workmanager.MyWorkManager3;
import com.maniu.mn_vip_jetpack_other.workmanager.MyWorkManager4;
import com.maniu.mn_vip_jetpack_other.workmanager.MyWorkManager5;

import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void test(View view) {
        // 单一的任务  一次
        OneTimeWorkRequest oneTimeWorkRequest1;

        // 数据
        Data sendData = new Data.Builder().putString("data", "提供给manager的数据").build();

        // 请求对象初始化
        oneTimeWorkRequest1 = new OneTimeWorkRequest.Builder(MyWorkManager.class)
                .setInputData(sendData) // 数据的携带
                .build();

        WorkManager.getInstance(this).getWorkInfoByIdLiveData(oneTimeWorkRequest1.getId())
                .observe(this, new Observer<WorkInfo>() {
                    @Override
                    public void onChanged(WorkInfo workInfo) {
                        Log.e(MyWorkManager.TAG, "Activity取到了任务回传的数据: " +
                                workInfo.getOutputData().getString("data"));

                        Log.e(MyWorkManager.TAG, "执行状态：" + workInfo.getState().name());
                        if (workInfo.getState().isFinished()) {
                            Log.e(MyWorkManager.TAG, "执行状态：isFinished=true 后台任务已经完成了...");
                        }
                    }
                });

        // 请求对象 加入到队列
        WorkManager.getInstance(this).enqueue(oneTimeWorkRequest1);
    }

    public void test2(View view) {
        OneTimeWorkRequest oneTimeWorkRequest2 =
                new OneTimeWorkRequest.Builder(MyWorkManager2.class).build();
        OneTimeWorkRequest oneTimeWorkRequest3 =
                new OneTimeWorkRequest.Builder(MyWorkManager3.class).build();
        OneTimeWorkRequest oneTimeWorkRequest4 =
                new OneTimeWorkRequest.Builder(MyWorkManager4.class).build();
        OneTimeWorkRequest oneTimeWorkRequest5 =
                new OneTimeWorkRequest.Builder(MyWorkManager5.class).build();
        // 顺序执行
        WorkManager.getInstance(this).beginWith(oneTimeWorkRequest2)
                .then(oneTimeWorkRequest3)
                .then(oneTimeWorkRequest4)
                .then(oneTimeWorkRequest5)
                .enqueue();
    }

    public void test3(View view) {
        // 重复的任务  多次  循环  , 最少循环重复 15分钟每次（少于15分钟默认为15分钟）
        PeriodicWorkRequest periodicWorkRequest =
                new PeriodicWorkRequest.Builder(MyWorkManager2.class, 20,
                        TimeUnit.SECONDS).build();

        // 监听状态
        WorkManager.getInstance(this).getWorkInfoByIdLiveData(periodicWorkRequest.getId())
                .observe(this, new Observer<WorkInfo>() {
                    @Override
                    public void onChanged(WorkInfo workInfo) {
                        Log.d(MyWorkManager2.TAG, "状态：" + workInfo.getState().name());
                        if (workInfo.getState().isFinished()) {
                            Log.d(MyWorkManager2.TAG, "状态：isFinished=true 后台任务已经完成了...");
                        }
                    }
                });

        WorkManager.getInstance(this).enqueue(periodicWorkRequest);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void test4(View view) {
        // 约束条件，必须满足我的条件，才能执行后台任务 （在连接网络，插入电源 并且 处于空闲时）  内部做了电量优化（Android App 不耗电）
        Constraints myConstraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED) // 网络链接中...
//                .setRequiresCharging(true) // 充电中..
//                .setRequiresDeviceIdle(true) // 空闲时.. (cpu使用率低)
                .build();

        /**
         * 除了上面设置的约束外，WorkManger还提供了以下的约束作为Work执行的条件：
         *  setRequiredNetworkType：网络连接设置
         *  setRequiresBatteryNotLow：是否为低电量时运行 默认false
         *  setRequiresCharging：是否要插入设备（接入电源），默认false
         *  setRequiresDeviceIdle：设备是否为空闲，默认false
         *  setRequiresStorageNotLow：设备可用存储是否不低于临界阈值
         */

        // 数据
        Data sendData = new Data.Builder().putString("data", "提供给manager的数据").build();

        // 请求对象
        OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(MyWorkManager2.class)
                .setConstraints(myConstraints)
                .setInputData(sendData) // 数据的携带
                .build();

        // 测试：监听状态
        // 监听状态
        WorkManager.getInstance(this).getWorkInfoByIdLiveData(request.getId())
                .observe(this, new Observer<WorkInfo>() {
                    @Override
                    public void onChanged(WorkInfo workInfo) {
                        Log.e(MyWorkManager2.TAG, "Activity取到了任务回传的数据: " +
                                workInfo.getOutputData().getString("data"));
                        Log.d(MyWorkManager2.TAG, "状态：" + workInfo.getState().name()+Thread.currentThread().getName());
                        if (workInfo.getState().isFinished()) {
                            Log.d(MyWorkManager2.TAG, "状态：isFinished=true 后台任务已经完成了...");
                        }
                    }
                });

        // 加入队列
        WorkManager.getInstance(this).enqueue(request);
    }
}
