package lt.vilnius.tvarkau.fragments;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;

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.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
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 java.util.HashMap;

import lt.vilnius.tvarkau.ProblemDetailActivity;
import lt.vilnius.tvarkau.R;
import lt.vilnius.tvarkau.entity.Problem;
import lt.vilnius.tvarkau.factory.DummyProblems;
import lt.vilnius.tvarkau.utils.PermissionUtils;
import lt.vilnius.tvarkau.views.adapters.MapsInfoWindowAdapter;

/**
 * Created by Karolis Vycius on 2016-01-13.
 */
public class ProblemsMapFragment extends SupportMapFragment
        implements OnMapReadyCallback,
        GoogleMap.OnInfoWindowClickListener,
        GoogleMap.OnInfoWindowCloseListener,
        GoogleMap.OnMarkerClickListener {

    protected static final LatLng VILNIUS_LAT_LNG = new LatLng(54.687157, 25.279652);
    protected static final int GPS_PERMISSION_REQUEST_CODE = 11;

    protected GoogleMap googleMap;

    protected BitmapDescriptor inProgressMarker;
    protected BitmapDescriptor doneMarker;

    protected HashMap<String, Problem> problemHashMap = new HashMap<>();

    public static ProblemsMapFragment getInstance() {
        return new ProblemsMapFragment();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        setMarkerResources();

        getMapAsync(this);
    }

    private void setMarkerResources() {
        inProgressMarker = BitmapDescriptorFactory.fromResource(R.drawable.ic_pin_drop_blue);
        doneMarker = BitmapDescriptorFactory.fromResource(R.drawable.ic_pin_drop_green);
    }

    protected void requestGPSPermission() {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            googleMap.setMyLocationEnabled(true);
        } else {
            PermissionUtils.verifyAndRequestPermissions(getActivity(), GPS_PERMISSION_REQUEST_CODE,
                    Manifest.permission.ACCESS_FINE_LOCATION);
        }
    }

    @Override
    public void onMapReady(GoogleMap map) {
        googleMap = map;
        map.setOnInfoWindowClickListener(this);
        map.setOnInfoWindowCloseListener(this);
        map.setOnMarkerClickListener(this);

        map.moveCamera(CameraUpdateFactory.newLatLngZoom(VILNIUS_LAT_LNG, 10f));

        requestGPSPermission();


        for (Problem problem : DummyProblems.getProblems()) {
            String problemStringId = String.valueOf(problem.getId());

            // Hack: Google Map don't have setData method.
            // There is no easy way to get problem from marker.
            // Set problem id as marker title and keep hashmap of problems with ids
            problemHashMap.put(problemStringId, problem);

            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(problem.getLatLng());
            markerOptions.title(problemStringId);

            switch (problem.getStatusCode()) {
                case Problem.STATUS_IN_PROGRESS:
                    markerOptions.icon(inProgressMarker);
                    break;
                case Problem.STATUS_DONE:
                    markerOptions.icon(doneMarker);
                    break;
            }

            map.addMarker(markerOptions);
        }

        map.setInfoWindowAdapter(new MapsInfoWindowAdapter(getActivity(), problemHashMap));

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == GPS_PERMISSION_REQUEST_CODE) {
            if (permissions.length >= 1 &&
                    permissions[0] == Manifest.permission.ACCESS_FINE_LOCATION &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Try/catch is used only to suppress permission grant error. It's impossible scenario.
                try {
                    googleMap.setMyLocationEnabled(true);
                    googleMap.getUiSettings().setMyLocationButtonEnabled(true);
                } catch (SecurityException securityException) {

                }
            }
        }
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
        int problemId = getProblemByMarker(marker).getId();

        Intent intent = ProblemDetailActivity.getStartActivityIntent(getActivity(), problemId);

        startActivity(intent);
    }

    @Override
    public void onInfoWindowClose(Marker marker) {
        getActivity().setTitle(R.string.title_problems_map);
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        getActivity().setTitle(getProblemByMarker(marker).getAddress());
        return false;
    }

    public Problem getProblemByMarker(Marker marker) {
        return problemHashMap.get(marker.getTitle());
    }
}

@@ -156,16 +156,59 @@
 Bundle;%0A
+import android.support.annotation.NonNull;%0A
 import a
@@ -1614,16 +1614,63 @@
 eMarker;
+%0A    protected BitmapDescriptor selectedMarker;
 %0A%0A    pr
@@ -2259,16 +2259,107 @@
 green);%0A
+        selectedMarker = BitmapDescriptorFactory.fromResource(R.drawable.ic_pin_drop_red);%0A
     %7D%0A%0A 
@@ -3720,324 +3720,64 @@
 d);%0A
-%0A            switch (problem.getStatusCode()) %7B%0A                case Problem.STATUS_IN_PROGRESS:%0A                    markerOptions.icon(inProgressMarker);%0A                    break;%0A                case Problem.STATUS_DONE:%0A                    markerOptions.icon(doneMarker);%0A                    break;%0A            %7D
+            markerOptions.icon(getMarkerIcon(problem));%0A
 %0A%0A  
@@ -3915,25 +3915,24 @@
 mHashMap));%0A
-%0A
     %7D%0A%0A    @
@@ -3999,16 +3999,25 @@
 estCode,
+ @NonNull
  String%5B
@@ -4030,16 +4030,25 @@
 issions,
+ @NonNull
  int%5B%5D g
@@ -4632,61 +4632,307 @@
 ion 
-securityException) %7B%0A%0A                %7D%0A            %7D
+ignored) %7B%0A%0A                %7D%0A            %7D%0A        %7D%0A    %7D%0A%0A    public BitmapDescriptor getMarkerIcon(Problem problem) %7B%0A        switch (problem.getStatusCode()) %7B%0A            case Problem.STATUS_DONE:%0A                return doneMarker;%0A            default:%0A                return inProgressMarker;
 %0A   
@@ -5263,32 +5263,87 @@
 arker marker) %7B%0A
+        Problem problem = getProblemByMarker(marker);%0A%0A
         getActiv
@@ -5387,16 +5387,64 @@
 s_map);%0A
+        marker.setIcon(getMarkerIcon(problem));%0A
     %7D%0A%0A 
@@ -5575,24 +5575,65 @@
 Address());%0A
+        marker.setIcon(selectedMarker);%0A%0A
         retu

Change marker color on selection