package projet.iut.jeu_de_la_vie.view.fragment;

import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import projet.iut.jeu_de_la_vie.R;
import projet.iut.jeu_de_la_vie.model.Manager;
import projet.iut.jeu_de_la_vie.model.boucleDeJeu.observer.ObservableBDJ;
import projet.iut.jeu_de_la_vie.model.boucleDeJeu.observer.ObserverBDJ;
import projet.iut.jeu_de_la_vie.model.cellule.Cellule;
import projet.iut.jeu_de_la_vie.model.cellulesVivantes.observer.ObserverCV;
import projet.iut.jeu_de_la_vie.view.LauncherActivity;
import projet.iut.jeu_de_la_vie.view.PlateauView;

public class FragmentPlateau extends Fragment implements ObserverBDJ {

    private Manager manager;
    public FragmentPlateau(){
        super(R.layout.fragment_plateau); //<-- lui passer la future vue du jeu
        manager = new Manager();
        ((ObservableBDJ) manager.getBoucleDeJeu()).attacher(this);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        manager.setNumberOfLines((Integer) getArguments().get("lignes"));
        manager.setNumberOfColumns((Integer) getArguments().get("colones"));
        if (savedInstanceState != null){
            manager = (Manager) savedInstanceState.getSerializable("manager");
        }
    }


    @Override
    public void onViewCreated (@NonNull View view, Bundle savedInstanceState){
        Log.d("fragment",isAdded()+"");
        PlateauView plateauView = view.findViewById(R.id.plateauView);
        plateauView.setLignes(manager.getNumberOfLines());
        plateauView.setColones(manager.getNomberOfColumns());
        plateauView.setOnTouchListener(this::tapRect);
        Button button = view.findViewById(R.id.startnstopButton);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(manager.isJeuLance())
                {
                    ((Button) view).setText("Start");
                    manager.stoperJeu();
                }else {
                    ((Button) view).setText("Stop");
                    manager.lancerJeu();
                }
            }
        });
    }

    private boolean tapRect(View view1, MotionEvent motionEvent){
        int x = -1;
        int y = -1;
        PlateauView plateauView = (PlateauView) view1;
        if (plateauView.isFormule()) {
            x = (int) (( (float) manager.getNomberOfColumns() / view1.getWidth()) * motionEvent.getX()-5/100);
            y = (int) (( (float) manager.getNomberOfColumns() / view1.getWidth()) * motionEvent.getY()-5/100);
        }
        else {
            x = (int) (( (float) manager.getNumberOfLines() / view1.getHeight()) * motionEvent.getX()-5/100);
            y = (int) (( (float) manager.getNumberOfLines() / view1.getHeight() ) * motionEvent.getY()-5/100);
        }
        return tapRect(view1, x, y);
    }
    private  boolean tapRect(View view, int x, int y){
        Log.d("D", "x=" + x);
        Log.d("D", "y=" + y);
        try {
            manager.updateOnCellBeforeStart(x, y);
            Cellule cellule = manager.getCell(x, y);
            if(cellule.isAlive()) {
                ((PlateauView) view).addPosCell(cellule);
            }else {
                ((PlateauView) view).delPosCell(cellule);
            }
        }catch (IllegalArgumentException e){
            Log.w("WARNING", e.getMessage());
        }
        return false;
    }

    @Override
    public void onInflate(@NonNull Context context, @NonNull AttributeSet attrs, @Nullable Bundle savedInstanceState) {
        super.onInflate(context, attrs, savedInstanceState);
    }

    @Override
    public void update() {
        try {

            PlateauView view = (PlateauView) getView().findViewById(R.id.plateauView);
            if (view == null) {
                return;
            }
            view.resetMap();
            for (Cellule c : manager.getActualiseurCellule().getArbitre().getPlateau().getCellulesVivantes().getCells().values()) {
                view.addPosCell(c);
            }
            view.postInvalidate();
        }
        catch (Exception e){

        }
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("manager",manager);
    }
}
