package com.atmob.mobile_use_statistics.core;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Looper;

import com.atmob.mobile_use_statistics.bean.DeviceUsageInfo;
import com.atmob.mobile_use_statistics.utils.LogUtil;
import com.atmob.mobile_use_statistics.utils.ParamUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel.Result;

public class FlutterUsageHelper {

    private static final String TAG = "UsagePermissions";

    public static void requestUseStatisticsPermission(Activity activity, Result result) {
        UsageStats.requestPermission(activity);

        LogUtil.d(TAG, "requestUseStatisticsPermission 申请使用统计权限");
        Application application = activity.getApplication();
        Application.ActivityLifecycleCallbacks lifecycleCallbacks = new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityResumed(Activity resumedActivity) {
                boolean granted = UsageStats.hasPermission(resumedActivity);
                LogUtil.d(TAG, "requestUseStatisticsPermission granted: " + granted);
                if (granted) {
                    result.success(true);
                } else {
                    result.success(false);
                }
                // 3. 注销监听器
                application.unregisterActivityLifecycleCallbacks(this);
            }

            // 其他生命周期回调不处理
            @Override
            public void onActivityCreated(Activity a, android.os.Bundle b) {
            }

            @Override
            public void onActivityStarted(Activity a) {
            }

            @Override
            public void onActivityPaused(Activity a) {
            }

            @Override
            public void onActivityStopped(Activity a) {
            }

            @Override
            public void onActivitySaveInstanceState(Activity a, android.os.Bundle b) {
            }

            @Override
            public void onActivityDestroyed(Activity a) {
            }
        };

        application.registerActivityLifecycleCallbacks(lifecycleCallbacks);
    }


    public static void hasUseStatisticsPermission(Context context, Result result) {
        boolean hasPermission = UsageStats.hasPermission(context);
        LogUtil.d(TAG, "hasUseStatisticsPermission: " + hasPermission);
        if (hasPermission) {
            result.success(true);
        } else {
            result.success(false);
        }
    }

    public static void getLockScreenStatistics(Activity activity, MethodCall call, Result result) {
        LogUtil.i(TAG, "getLockScreenStatistics===>" + call.arguments());
        Map<String, Object> arguments = call.arguments();
        if (arguments == null || arguments.isEmpty()) {
            result.error("-1", "getLockScreenStatistics.arguments is empty", null);
            return;
        }
        Long startTime = ParamUtil.getLong(arguments, "startTime");
        Long endTime = ParamUtil.getLong(arguments, "endTime");
        if (startTime == null || endTime == null) {
            result.error("-1", "getLockScreenStatistics arguments must contain startTime and endTime", null);
            return;
        }
        if (startTime > endTime) {
            result.error("-1", "Invalid time range: startTime=" + startTime + " endTime=" + endTime, null);
            return;
        }

        new Thread(() -> {
            try {
                //目前仅返回设备事件
                List<DeviceUsageInfo.Event> resultEvent = UsageStats.queryAndAggregateAppUsageData(activity, startTime, endTime);
                List<Map<String, Object>> eventMapList = new ArrayList<>();
                if (resultEvent != null) {
                    for (DeviceUsageInfo.Event event : resultEvent) {
                        eventMapList.add(event.toMap());
                    }
                }
                activity.runOnUiThread(() -> result.success(eventMapList));
            } catch (Exception e) {
                LogUtil.e(TAG, "getLockScreenStatistics error: " + e.getMessage());
                activity.runOnUiThread(() -> result.error("-1", "getLockScreenStatistics error: " + e.getMessage(), null));
            }
        }).start();
    }
}
