package org.keyscience.app;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ContextThemeWrapper;
import android.support.v7.view.menu.MenuBuilder;
import android.support.v7.view.menu.MenuPopupHelper;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PointOfInterest;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.Polyline;
import com.google.maps.android.data.Feature;
import com.google.maps.android.data.Layer;
import com.google.maps.android.data.kml.KmlContainer;
import com.google.maps.android.data.kml.KmlGroundOverlay;
import com.google.maps.android.data.kml.KmlLayer;
import com.google.maps.android.data.kml.KmlPlacemark;

import org.keyscience.R;
import org.keyscience.adapters.ExploreTheKeyAdapter;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.List;

public class ExploreTheKey extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    private Toolbar toolbar;
    private FloatingActionButton fab;
    private View beach;
    private View coral;
    private View green;
    private View path;
    private View seagrass;
    private View water;
    private LatLng KeyBiscayne = new LatLng(25.700766, -80.157774);
    private float zoom = 13;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_explore_the_key);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        setUpToolBar();

        //*********************
        //set up bottom sheets
        beach = findViewById(R.id.beaches_info);
        coral = findViewById(R.id.coral_info);
        green = findViewById(R.id.green_info);
        path = findViewById(R.id.path_info);
        seagrass = findViewById(R.id.seagrass_info);
        water = findViewById(R.id.water_info);

        resetInfo();// hide them until one layer is selected
        //*********************

        fab = findViewById(R.id.maps_action_button);

        Context wrapper = new ContextThemeWrapper(ExploreTheKey.this, R.style.PopUpMenuStyle);
        final PopupMenu popup = new PopupMenu(ExploreTheKey.this, fab);
        popup.inflate(R.menu.menu_map_layers);
        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                resetIcons(popup);
                resetInfo();
                switch (menuItem.getItemId()) {
                    case R.id.beach_layer:
                        beach.setVisibility(View.VISIBLE);
                        menuItem.setIcon(R.drawable.ic_beaches_blue);
                        setMapLayer(mMap, R.raw.csp_beaches);
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(KeyBiscayne, zoom));
                        return true;
                    case R.id.coralfeef_layer:
                        coral.setVisibility(View.VISIBLE);
                        menuItem.setIcon(R.drawable.ic_coralreef_blue);
                        setMapLayer(mMap, R.raw.csp_coralreefs);
                        // move the came to the reef area
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(25.703394, -80.090000), 12));
                        return true;
                    case R.id.green_layer:
                        green.setVisibility(View.VISIBLE);
                        menuItem.setIcon(R.drawable.ic_greenareas_blue);
                        setMapLayer(mMap, R.raw.csp_green);
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(KeyBiscayne, zoom));
                        return true;
                    case R.id.pathways_layer:
                        path.setVisibility(View.VISIBLE);
                        menuItem.setIcon(R.drawable.ic_pathways_blue);
                        setMapLayer(mMap, R.raw.csp_pathways);
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(KeyBiscayne, zoom));
                        return true;
                    case R.id.seagrass_layer:
                        seagrass.setVisibility(View.VISIBLE);
                        menuItem.setIcon(R.drawable.ic_seagrass_blue);
                        setMapLayer(mMap, R.raw.csp_seagrasses);
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(KeyBiscayne, zoom));
                        return true;
                    case R.id.water_layer:
                        water.setVisibility(View.VISIBLE);
                        menuItem.setIcon(R.drawable.ic_water_ways_blue);
                        setMapLayer(mMap, R.raw.csp_water);
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(KeyBiscayne, zoom));
                        return true;
                }
                return false;
            }
        });
        final MenuPopupHelper menuHelper = new MenuPopupHelper(wrapper, (MenuBuilder) popup.getMenu(), fab);
        menuHelper.setForceShowIcon(true);
        menuHelper.setGravity(Gravity.END);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                menuHelper.show();
            }
        });
    }

    private void resetInfo() {
        beach.setVisibility(View.INVISIBLE);
        coral.setVisibility(View.INVISIBLE);
        green.setVisibility(View.INVISIBLE);
        path.setVisibility(View.INVISIBLE);
        seagrass.setVisibility(View.INVISIBLE);
        water.setVisibility(View.INVISIBLE);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        setMapLayer(mMap, R.raw.csp_beaches);
        beach.setVisibility(View.VISIBLE);

        // Add a marker in KeyBiscayne and move the camera
        float zoom = 13;
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(KeyBiscayne, zoom));

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_map_terrain, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.standard_map:
                mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                break;
            case R.id.hybrid_map:
                mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                break;
            case R.id.satellite_map:
                mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
                break;
            case R.id.terrain_map:
                mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
                break;
        }


        return true;
    }

    /**
     * Add marker and show information upon selection
     *
     * @param map
     */
    private void setPoiClick(final GoogleMap map) {
        map.setOnPoiClickListener(new GoogleMap.OnPoiClickListener() {
            @Override
            public void onPoiClick(PointOfInterest poi) {
                map.clear(); // clear previously selected poi
                Marker poiMarker = mMap.addMarker(new MarkerOptions()
                        .position(poi.latLng)
                        .title(poi.name));

                poiMarker.showInfoWindow();

            }
        });
    }

    private void setUpToolBar() {
        // setup toolbar as action bar
        toolbar = findViewById(R.id.maps_toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle(Constants.TITLE);
        toolbar.setSubtitle(Constants.CITIZEN_SCIENTIST_PROJECT);
    }

    private void setMapLayer(GoogleMap mMap, int layerFile) {
        mMap.clear();
        final KmlLayer layer;
        try {
            layer = new KmlLayer(mMap, layerFile, getApplicationContext());
           layer.addLayerToMap();
            mMap.setInfoWindowAdapter(new ExploreTheKeyAdapter(getApplicationContext()));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }
    }

    public void resetIcons(PopupMenu popup) {
        popup.getMenu().findItem(R.id.beach_layer).setIcon(R.drawable.ic_beaches);
        popup.getMenu().findItem(R.id.coralfeef_layer).setIcon(R.drawable.ic_coralreef);
        popup.getMenu().findItem(R.id.green_layer).setIcon(R.drawable.ic_greenareas);
        popup.getMenu().findItem(R.id.pathways_layer).setIcon(R.drawable.ic_pathways);
        popup.getMenu().findItem(R.id.seagrass_layer).setIcon(R.drawable.ic_seagrass);
        popup.getMenu().findItem(R.id.water_layer).setIcon(R.drawable.ic_water_ways);
    }
}
