package com.atmob.flutter_umeng;

import android.content.Context;
import androidx.annotation.NonNull;
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;

/**
 * FlutterUmengPlugin
 */
public class FlutterUmengPlugin 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 static final String METHOD_POLICY_GRANT = "setPolicyGrantResult";
    private static final String METHOD_INIT_COMMON = "initCommon";

    private Context applicationContext;


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

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        switch (call.method) {
            case METHOD_POLICY_GRANT:
                setPolicyGrantResult(call, result);
                break;
            case METHOD_INIT_COMMON:
                initCommon(call, result);
                break;
            default:
                result.notImplemented();
        }
    }

    private void initCommon(MethodCall call, Result result) {
        if (applicationContext == null) {
            result.error("-1", "applicationContext is null", null);
            return;
        }
        try {
            String appKey = call.argument("appKey");
            UmengHelper.initCommon(applicationContext, appKey);
            result.success(null);
        } catch (Exception e) {
            result.error("-1", e.getMessage(), null);
        }
    }

    private void setPolicyGrantResult(MethodCall call, Result result) {
        if (applicationContext == null) {
            result.error("-1", "applicationContext is null", null);
            return;
        }
        try {
            boolean granted = Boolean.TRUE.equals(call.argument("granted"));
            UmengHelper.submitPolicyGrantResult(applicationContext, granted);
            result.success(null);
        } catch (Exception e) {
            result.error("-1", e.getMessage(), null);
        }
    }

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