package com.example.reticule;

import android.content.Context;
import android.content.SharedPreferences;
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 android.util.TypedValue;

public class ReticleView extends View {
    private float reticleX, reticleY;
    private final float radius = 50; // Taille du réticule
    private float lastTouchX, lastTouchY;
    private final Paint paint;
    private static final String PREFS_NAME = "ReticlePrefs";
    private static final String KEY_X = "reticle_x";
    private static final String KEY_Y = "reticle_y";

    public ReticleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.FILL);

        loadReticlePosition();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(reticleX, reticleY, radius, paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float touchX = event.getX();
        float touchY = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastTouchX = touchX;
                lastTouchY = touchY;
                break;

            case MotionEvent.ACTION_MOVE:
                float dx = touchX - lastTouchX;
                float dy = touchY - lastTouchY;

                if (Math.abs(dx) > dpToPx(10) || Math.abs(dy) > dpToPx(10)) {
                    reticleX += dx;
                    reticleY += dy;
                    lastTouchX = touchX;
                    lastTouchY = touchY;
                    invalidate();
                }
                break;

            case MotionEvent.ACTION_UP:
                saveReticlePosition();
                break;
        }
        return true;
    }

    private void saveReticlePosition() {
        SharedPreferences prefs = getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putFloat(KEY_X, reticleX);
        editor.putFloat(KEY_Y, reticleY);
        editor.apply();
    }

    private void loadReticlePosition() {
        SharedPreferences prefs = getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        reticleX = prefs.getFloat(KEY_X, getWidth() / 2f);
        reticleY = prefs.getFloat(KEY_Y, getHeight() / 2f);
        if (reticleX == 0 || reticleY == 0) {
            reticleX = getWidth() / 2f;
            reticleY = getHeight() / 2f;
        }
    }

    private float dpToPx(float dp) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }
}
