package com.atmob.mobile_use_statistics;

import android.app.Activity;
import android.content.Context;

import androidx.annotation.NonNull;

import com.atmob.mobile_use_statistics.core.FlutterUsageHelper;
import com.atmob.mobile_use_statistics.utils.LogUtil;

import java.util.Objects;

import io.flutter.BuildConfig;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/**
 * MobileUseStatisticsPlugin
 */
public class MobileUseStatisticsPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private MethodChannel channel;

    private Context context;

    private Activity activity;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        LogUtil.setLogEnabled(BuildConfig.DEBUG);
        context = flutterPluginBinding.getApplicationContext();
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "mobile_use_statistics");
        channel.setMethodCallHandler(this);
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        String method = call.method;
        if (Objects.equals(method, "requestUseStatisticsPermission")) {
            FlutterUsageHelper.requestUseStatisticsPermission(activity, result);
        } else if (Objects.equals(method, "hasUseStatisticsPermission")) {
            FlutterUsageHelper.hasUseStatisticsPermission(context, result);
        } else if (Objects.equals(method, "getLockScreenStatistics")) {
            FlutterUsageHelper.getLockScreenStatistics(activity, call, result);
        } else {
            result.notImplemented();
        }
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }

    @Override
    public void onAttachedToActivity(@NonNull ActivityPluginBinding activityPluginBinding) {
        this.activity = activityPluginBinding.getActivity();

    }

    @Override
    public void onDetachedFromActivityForConfigChanges() {

    }

    @Override
    public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding activityPluginBinding) {

    }

    @Override
    public void onDetachedFromActivity() {
        this.activity = null;
    }
}
