package com.atmob.flutter_tool_android;

import android.content.Context;
import android.content.Intent;

import androidx.annotation.NonNull;

import com.atmob.flutter_tool_android.utils.BackgroundPermissionUtil;
import com.atmob.flutter_tool_android.utils.BatteryUtil;

import java.util.Objects;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
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;

/**
 * FlutterToolAndroidPlugin
 */
public class FlutterToolAndroidPlugin implements FlutterPlugin, MethodCallHandler {
    /// 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;

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

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        String method = call.method;
        if (Objects.equals(method, "isIgnoringBatteryOptimizations")) {
            result.success(BatteryUtil.isIgnoringBatteryOptimizations(context));
        } else if (Objects.equals(method, "openBatteryOptimizationSettings")) {
            BatteryUtil.openBatteryOptimizationSettings(context);
            result.success(null);
        } else if (Objects.equals(method, "openAppBackgroundSetting")) {
            BackgroundPermissionUtil.requestBackgroundPermission(context);
            result.success(null);
        } else if (Objects.equals(method, "backHome")) {
            try {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
            result.success(null);
        } else {
            result.notImplemented();
        }
    }

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