package com.atmob.map_amap_android.event;

import androidx.annotation.NonNull;

import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.atmob.map_amap_android.contants.Constants;
import com.atmob.map_amap_android.util.LogUtil;

import java.util.HashMap;
import java.util.Map;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.EventChannel;

public class FlutterCameraChangeEventPlugin implements FlutterPlugin, EventChannel.StreamHandler {

    private static final String TAG = "FlutterCameraChangeEventPlugin";

    private EventChannel eventChannel;
    private EventChannel.EventSink eventSink;
    private Map<String, Object> locationMap;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        eventChannel = new EventChannel(flutterPluginBinding.getBinaryMessenger(), Constants.MAP_CAMERA_CHANGE_EVENT_CHANNEL);
        eventChannel.setStreamHandler(this);
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        if (eventChannel != null) {
            eventChannel.setStreamHandler(null);
        }
        eventChannel = null;
        eventSink = null;
        if (locationMap != null) locationMap.clear();
        locationMap = null;
    }

    @Override
    public void onListen(Object o, EventChannel.EventSink eventSink) {
        this.eventSink = eventSink;
    }

    @Override
    public void onCancel(Object o) {
        eventSink = null;
        if (locationMap != null) locationMap.clear();
        locationMap = null;
    }


    public void senCameraChange(String function, CameraPosition cameraPosition) {
        try {
            if (eventSink != null) {
                Map<String, Object> data = obtainData(function, cameraPosition);
                eventSink.success(data);
                LogUtil.d(TAG, "senCameraChange success: " + data);
            }
        } catch (Exception e) {
            LogUtil.d(TAG, "senCameraChange error: " + e.getMessage());
            sendError("-1", e.getMessage());
        }
    }

    private void sendError(String errorCode, String errorMessage) {
        if (eventSink != null) {
            eventSink.error(errorCode, errorMessage, null);
        }
    }

    private Map<String, Object> obtainData(String function, CameraPosition cameraPosition) {
        if (locationMap == null) {
            locationMap = new HashMap<>(4);
        }
        locationMap.clear();
        LatLng target = cameraPosition.target;
        locationMap.put("function", function);
        locationMap.put("longitude", target.longitude);
        locationMap.put("latitude", target.latitude);
        locationMap.put("zoom", cameraPosition.zoom);
        return locationMap;
    }
}
