package com.example.pois;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class Pois extends View {

    private final Paint paint;
    private final Map<Integer, float[]> touches; // Stocke les coordonnées des touches
    private final Map<Integer, Integer> colors;  // Stocke la couleur de chaque touche

    public Pois(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.FILL);
        touches = new HashMap<>();
        colors = new HashMap<>();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (Map.Entry<Integer, float[]> entry : touches.entrySet()) {
            int pointerId = entry.getKey();
            float[] position = entry.getValue();
            paint.setColor(colors.get(pointerId)); // Applique la couleur associée
            canvas.drawCircle(position[0], position[1], 50, paint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int pointerIndex = event.getActionIndex();
        int pointerId = event.getPointerId(pointerIndex);

        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_POINTER_DOWN:
                // Ajouter une nouvelle touche avec une couleur aléatoire
                touches.put(pointerId, new float[]{event.getX(pointerIndex), event.getY(pointerIndex)});
                if (!colors.containsKey(pointerId)) {
                    colors.put(pointerId, getRandomColor());
                }
                invalidate();
                break;

            case MotionEvent.ACTION_MOVE:
                // Mise à jour des positions des doigts
                for (int i = 0; i < event.getPointerCount(); i++) {
                    int id = event.getPointerId(i);
                    touches.put(id, new float[]{event.getX(i), event.getY(i)});
                }
                invalidate();
                break;

            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                // Retirer le point de contact mais garder sa couleur
                touches.remove(pointerId);
                invalidate();
                break;
        }
        return true;
    }

    private int getRandomColor() {
        int[] colorsList = {Color.MAGENTA, Color.YELLOW, Color.CYAN, Color.RED, Color.GREEN, Color.BLUE};
        return colorsList[new Random().nextInt(colorsList.length)];
    }
}