package com.m2sdl.undercooked.map;

import android.content.Context;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.m2sdl.undercooked.InfoActivity;

import org.mapsforge.core.graphics.Bitmap;
import org.mapsforge.core.model.LatLong;
import org.mapsforge.core.model.Point;
import org.mapsforge.map.android.view.MapView;
import org.mapsforge.map.datastore.PointOfInterest;
import org.mapsforge.map.layer.overlay.Marker;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;

public class RestaurantMarker extends Marker {

    PointOfInterest pointOfInterest;
    MapView mapView;

    Context context;

    public RestaurantMarker(Context context, Bitmap bitmap, PointOfInterest pointOfInterest, MapView mapView) {
        super(pointOfInterest.position, bitmap, 0, 0);
        setDisplayModel(mapView.getModel().displayModel);
        TOUCH_SIZE = 20;
        this.context = context;
        this.pointOfInterest = pointOfInterest;
        this.mapView = mapView;
    }

    @NonNull
    @Override
    public String toString() {
        return "RestaurantMarker At: " + pointOfInterest.position + ",tags = " + pointOfInterest.tags;
    }

    @Override
    public boolean equals(Object o) {
        if (o == null || getClass() != o.getClass()) return false;
        RestaurantMarker that = (RestaurantMarker) o;
        return Objects.equals(pointOfInterest.position, that.pointOfInterest.position);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(pointOfInterest);
    }

    @Override
    public boolean onLongPress(LatLong tapLatLong, Point layerXY, Point tapXY) {
        if (markerWasPressed(tapXY)) {
            Toast.makeText(context, name(), Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }

    private boolean markerWasPressed(Point tapXY) {
        var layerXY = mapView.getMapViewProjection().toPixels(getPosition());
        return contains(layerXY, tapXY, mapView);
    }

    @Override
    public boolean onTap(LatLong tapLatLong, Point layerXY, Point tapXY) {
        if (markerWasPressed(tapXY)) {
            context.startActivity(InfoActivity.newIntent(context, position()));
            return true;
        }
        return false;
    }

    private String name() {
        AtomicReference<String> name = new AtomicReference<>();
        pointOfInterest.tags.forEach(
                tag -> {
                    if (Objects.equals(tag.key, "name")) {
                        name.set(tag.value);
                    }
                }
        );
        return name.get();
    }

    private LatLong position() {
        return pointOfInterest.position;
    }
}
