package com.android.chmo.ui.activity.message;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.android.chmo.R;
import com.android.chmo.base.BaseActivity;
import com.android.chmo.im.location.ChmoLocationManager;
import com.android.chmo.ui.view.TopBar;
import com.netease.nim.uikit.api.model.location.LocationProvider;
import com.netease.nim.uikit.common.framework.infra.DefaultTaskManager;
import com.netease.nim.uikit.common.framework.infra.DefaultTaskWorker;
import com.netease.nim.uikit.common.framework.infra.ManagedTask;
import com.netease.nim.uikit.common.framework.infra.TaskExecutor;
import com.netease.nim.uikit.common.framework.infra.TaskManager;

import butterknife.BindView;

/**
 * Created by Administrator on 2018/8/8.
 */

public class LocationMapActivity extends BaseActivity implements AMap.OnCameraChangeListener, AMapLocationListener {
    @BindView(R.id.topBar)
    TopBar topBar;

    @BindView(R.id.mapView)
    MapView mapView;
    @BindView(R.id.prompt)
    View promptView;

    @BindView(R.id.address)
    TextView addressView;

    AMap amap;

    ChmoLocationManager locationManager;

    private boolean locating = true; // 正在定位的时候不用去查位置

    private double latitude = 39.90923;
    private double longitude = 116.397428;
    private String addressInfo;

    private TaskManager taskManager;

    private static LocationProvider.Callback callback;

    public static void start(Context context, LocationProvider.Callback callback){
        LocationMapActivity.callback = callback;
        context.startActivity(new Intent(context, LocationMapActivity.class));
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_location_map;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mapView.onCreate(savedInstanceState);
    }

    @Override
    public void initView() {
        topBar.setRightBtn("发送", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendLocation();
            }
        });

        initAmap();
        initLocation();
    }

    private void initAmap() {
        try {
            amap = mapView.getMap();
            amap.setOnCameraChangeListener(this);

            UiSettings uiSettings = amap.getUiSettings();
            uiSettings.setZoomControlsEnabled(true);
            // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
            uiSettings.setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initLocation() {
        locationManager = new ChmoLocationManager(this, this);
        Location location = locationManager.getLastKnownLocation();

        if(null != location) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }

        Intent intent = getIntent();
        double lat = intent.getDoubleExtra("latitude", 0);
        double lon = intent.getDoubleExtra("longitude", 0);
        String address = intent.getStringExtra("address");
        if(lat != 0 && lon != 0) {
            latitude = lat;
            longitude = lon;
            addressInfo = address;
        }

       refreshLocationInfo();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        locationManager.stop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        locationManager.request();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (locationManager != null) {
            locationManager.stop();
        }
        if (taskManager != null) {
            taskManager.shutdown();
        }
        callback = null;
    }




    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        if (!locating) {
            queryLatLngAddress(cameraPosition.target);
        }

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            latitude = aMapLocation.getLatitude();
            longitude = aMapLocation.getLongitude();
            addressInfo = aMapLocation.getAddress();

            if (locating) {
                locating = false;
                refreshLocationInfo();
            }
        }
    }

    private void refreshLocationInfo() {
        promptView.setVisibility(View.VISIBLE);
        addressView.setText(addressInfo);
        CameraUpdate camera = CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(latitude, longitude), 15, 0, 0));
        amap.moveCamera(camera);
    }


    private void queryLatLngAddress(LatLng latLng) {
        if (!TextUtils.isEmpty(addressInfo) && latLng.latitude == latitude && latLng.longitude == longitude) {
            return;
        }
        latitude = latLng.latitude;
        longitude = latLng.longitude;


        if (taskManager == null) {
            TaskExecutor.Config config = new TaskExecutor.Config(0, 3, 30 * 1000, true);
            taskManager = new DefaultTaskManager(new DefaultTaskWorker("Location", config));
        }

        taskManager.cancelAll();
        taskManager.schedule(new ManagedTask() {
            @Override
            protected Object[] execute(Object[] params) {
                RegeocodeAddress address = locationManager.getLocationAddress(latitude, longitude);
                if(null != address) {
                    addressInfo = address.getFormatAddress();
                    refreshLocationInfo();
                }
                return null;
            }
        });

    }


    private void sendLocation() {
        Intent intent = new Intent();
        intent.putExtra("latitude", latitude);
        intent.putExtra("longitude", longitude);
        intent.putExtra("address", addressInfo);
        intent.putExtra("zoom_level", amap.getCameraPosition().zoom);
        intent.putExtra("img_url", getStaticMapUrl());

        if (callback != null) {
            callback.onSuccess(longitude, latitude, addressInfo);
        }
        finish();
    }

    private String getStaticMapUrl() {
        String STATIC_MAP_URL_1 = "http://maps.google.cn/maps/api/staticmap?size=200x100&zoom=13&markers=color:red|label:YourPosition|";
        String STATIC_MAP_URL_2 = "&maptype=roadmap&sensor=false&format=jpg";
        StringBuilder urlBuilder = new StringBuilder(STATIC_MAP_URL_1);
        urlBuilder.append(latitude);
        urlBuilder.append(",");
        urlBuilder.append(longitude);
        urlBuilder.append(STATIC_MAP_URL_2);
        return urlBuilder.toString();
    }

}
