package de.apps4ics.mountainnavigation.overlays;

import android.app.AlertDialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;

import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.OverlayItem;

import java.util.ArrayList;
import java.util.List;

import de.apps4ics.mountainnavigation.MainActivity;
import de.apps4ics.mountainnavigation.R;

/**
 * Created by Vinz on 03.11.2015.
 */
public class ImageDialogItemizedIconOverlay extends ItemizedIconOverlay<OverlayItem> {
    private Context context;
    private AlertDialog alertDialog;
    private List<Boolean> items;
    private Drawable posIcon;
    private Drawable negIcon;
    private MapView mapView;
    private int selected;

    public ImageDialogItemizedIconOverlay(final Context context, final List<OverlayItem> aList, AlertDialog alertDialog, MapView mapView) {
        super(context, aList, new OnItemGestureListener<OverlayItem>() {
            @Override
            public boolean onItemSingleTapUp(int index, OverlayItem item) {
                return false;
            }

            @Override
            public boolean onItemLongPress(int index, OverlayItem item) {
                return false;
            }
        });
        this.context = context;
        this.items = new ArrayList<>();
        this.alertDialog = alertDialog;
        this.mapView = mapView;
        selected = 0;
        Resources res = context.getResources();
        posIcon = res.getDrawable(R.mipmap.ic_poi);
        negIcon = res.getDrawable(R.mipmap.ic_poi_red);
        for(int i=0; i<aList.size(); ++i){
            items.add(false);
        }
    }

    private void updateItem(int index){
        if(items.get(index)){
            items.set(index, false);
            getItem(index).setMarker(negIcon);
            selected--;
        } else {
            items.set(index, true);
            getItem(index).setMarker(posIcon);
            selected++;
        }
        mapView.invalidate();
        checkForSelection(index);
    }

    private void checkForSelection(int index){
        if(selected == 1){
            MainActivity.imageMarker = getItem(index);
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
        } else {
            MainActivity.imageMarker = null;
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
        }
    }

    @Override
    protected boolean onSingleTapUpHelper(int index, OverlayItem item, MapView mapView) {
        updateItem(index);
        return true;
    }
}
