package com.example.arc_en_ciel;

import android.os.Bundle;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends Activity {
    private View colorBackground;
    private Button selectButton;
    private List<Integer> rainbowColors = Arrays.asList(
            Color.RED, Color.rgb(255, 165, 0), Color.YELLOW, Color.GREEN,
            Color.BLUE, Color.rgb(75, 0, 130), Color.rgb(148, 0, 211)
    );
    private List<Integer> activeColors = new ArrayList<>();
    private int currentColorIndex = 0;
    private static final String PREFS_NAME = "ColorPrefs";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        colorBackground = findViewById(R.id.colorBackground);
        selectButton = findViewById(R.id.selectButton);

        loadActiveColors();
        updateBackgroundColor();

        colorBackground.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (!activeColors.isEmpty()) {
                    currentColorIndex = (currentColorIndex + 1) % activeColors.size();
                    updateBackgroundColor();
                }
            }
            return true;
        });

        selectButton.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, ColorSelectionActivity.class);
            startActivity(intent);
        });
    }

    private void loadActiveColors() {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        activeColors.clear();

        for (int i = 0; i < rainbowColors.size(); i++) {
            if (prefs.getBoolean("color_" + i, true)) { // Par défaut, toutes les couleurs sont actives
                activeColors.add(rainbowColors.get(i));
            }
        }

        if (activeColors.isEmpty()) {
            activeColors.add(Color.GRAY); // Afficher une couleur par défaut si tout est décoché
        }
    }

    private void updateBackgroundColor() {
        if (!activeColors.isEmpty()) {
            colorBackground.setBackgroundColor(activeColors.get(currentColorIndex));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadActiveColors();
        currentColorIndex = 0;
        updateBackgroundColor();
    }
}