package com.example.admin.mygame;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.support.constraint.ConstraintLayout;
import android.support.constraint.ConstraintSet;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class Main2Activity extends AppCompatActivity implements View.OnClickListener{

    int nextTargetButtonNumber = 1;
    int numberOfButtons = 25;
    int row = 5;
    int col = 5;

    final int BUTTON_SIZE = 96+48;

    ArrayList<Button> buttons = new ArrayList<Button>();
    Button currentTargetButton = null;
    Button lastTargetButton = null;

    ConstraintLayout layout = null;
    ConstraintSet viewSet = null;

    //配置済みの場所を記憶する二次元配列
    boolean[][] isDeployed = new boolean[row][col];
    Button[][] invisibleButtons = new Button[row][col];

    long startTime = 0;
    long now = 0;
    long milliSecond = 0;
    long passedTime = 0;

    Timer timer = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        layout = new ConstraintLayout(this);

        final TextView timeView = new TextView(this);
        timeView.setId(View.generateViewId());
        layout.addView(timeView);

        //作ったtimeViewをlayoutに配置する
        viewSet = new ConstraintSet();
        viewSet.clone(layout);

        //配置の設定
        viewSet.connect(timeView.getId(),ConstraintSet.LEFT, ConstraintSet.PARENT_ID,ConstraintSet.LEFT);
        viewSet.connect(timeView.getId(),ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID,ConstraintSet.BOTTOM);

        setInvisibleButtons();

        Button resetButton = getAddedButtonWithSize(BUTTON_SIZE,BUTTON_SIZE);
        resetButton.setText("reset");
        final Context context = this;
        resetButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, MainActivity.class);
                if(timer != null){
                    timer.cancel();
                    timer = null;
                }
                startActivity(intent);
            }
        });
        viewSet.connect(resetButton.getId(),ConstraintSet.LEFT,ConstraintSet.PARENT_ID,ConstraintSet.LEFT);
        viewSet.connect(resetButton.getId(),ConstraintSet.RIGHT,ConstraintSet.PARENT_ID,ConstraintSet.RIGHT);
        viewSet.connect(resetButton.getId(),ConstraintSet.BOTTOM, timeView.getId(),ConstraintSet.TOP);
        viewSet.constrainWidth(resetButton.getId(), ConstraintSet.MATCH_CONSTRAINT);

        //ボタンを量産する。
        createButtons();

        currentTargetButton = buttons.get(0); //最初のボタンを決定
        lastTargetButton = buttons.get(buttons.size() - 1); //最後のボタンを設定

        //レイアウトをランダムにするfor文
        shuffleButtons();

        viewSet.applyTo(layout);

        setContentView(layout);

        startTimer(timeView);

    }

    private void createButtons(){
        for(int i = 0; i < numberOfButtons; i++) {
            Button button = getAddedButtonWithSize(BUTTON_SIZE,BUTTON_SIZE);
            button.setText(String.valueOf(i+1));
            button.setOnClickListener(this);
            buttons.add(button);

        }
    }

    private void shuffleButtons(){
        for(int i = 0; i < numberOfButtons; i++){
            //乱数を使用する
            Random rand = new Random();
            while(true){
                int leftViewId = rand.nextInt(col);
                int topViewId = rand.nextInt(row);

                if(isDeployed[topViewId][leftViewId]) {
                    continue;
                }

                viewSet.connect(buttons.get(i).getId(), ConstraintSet.LEFT, invisibleButtons[topViewId][leftViewId].getId(), ConstraintSet.LEFT);
                viewSet.connect(buttons.get(i).getId(), ConstraintSet.TOP, invisibleButtons[topViewId][leftViewId].getId(), ConstraintSet.TOP);
                isDeployed[topViewId][leftViewId] = true;
                break;
            }

        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        startTime = System.currentTimeMillis();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        now = System.currentTimeMillis();
        passedTime += (now - startTime);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(timer != null){
            timer.cancel();
            timer = null;
        }
    }

    @Override
    public void onClick(View view) {
        if (view == currentTargetButton && currentTargetButton == lastTargetButton){
            gameFinish();
        }else if(view == currentTargetButton){
            currentTargetButton.setVisibility(View.INVISIBLE);
            currentTargetButton = buttons.get(nextTargetButtonNumber);//ターゲット変更
            nextTargetButtonNumber++;//次のターゲットの番号
        }
    }

    private void gameFinish(){
        long time = passedTime + (now - startTime);
        SharedPreferences preferences = getSharedPreferences("best_time", MODE_PRIVATE);
        long bestTime = preferences.getLong("time", 99999999);
        if(time < bestTime) {
            SharedPreferences.Editor editor = preferences.edit();
            editor.putLong("time", passedTime + (now - startTime));
            editor.commit();
        }

        if(timer != null){
            timer.cancel();
            timer = null;
        }

        currentTargetButton.setVisibility(View.INVISIBLE);
        Toast.makeText(this,"finish", Toast.LENGTH_SHORT).show();
    }

    private Button getAddedButtonWithSize(int height, int width){
        Button button = new Button(this);
        button.setId(View.generateViewId());
        layout.addView(button);
        viewSet.constrainHeight(button.getId(), height);
        viewSet.constrainWidth(button.getId(), width);
        return button;
    }

    private void setInvisibleButtons(){
        invisibleButtons[0][0] = getAddedButtonWithSize(BUTTON_SIZE,BUTTON_SIZE);
        viewSet.connect(invisibleButtons[0][0].getId(), ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP);
        viewSet.connect(invisibleButtons[0][0].getId(), ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT);
        Button tmpButton = null;
        for(int j = 1; j < col; j++){
            tmpButton = getAddedButtonWithSize(BUTTON_SIZE, BUTTON_SIZE);
            viewSet.connect(tmpButton.getId(), ConstraintSet.LEFT, invisibleButtons[0][j-1].getId(),ConstraintSet.RIGHT);
            viewSet.connect(tmpButton.getId(), ConstraintSet.TOP, ConstraintSet.PARENT_ID,ConstraintSet.TOP);
            invisibleButtons[0][j] = tmpButton;
            tmpButton = null;
        }
        for(int i = 1; i < row; i++){
            tmpButton = getAddedButtonWithSize(BUTTON_SIZE, BUTTON_SIZE);
            viewSet.connect(tmpButton.getId(), ConstraintSet.LEFT, ConstraintSet.PARENT_ID,ConstraintSet.LEFT);
            viewSet.connect(tmpButton.getId(), ConstraintSet.TOP, invisibleButtons[i-1][0].getId(),ConstraintSet.BOTTOM);
            invisibleButtons[i][0] = tmpButton;
            tmpButton = null;
        }
        for(int i = 1; i < row; i++){
            for(int j = 1; j < col; j++){
                tmpButton = getAddedButtonWithSize(BUTTON_SIZE, BUTTON_SIZE);
                viewSet.connect(tmpButton.getId(), ConstraintSet.LEFT, invisibleButtons[i][j-1].getId(),ConstraintSet.RIGHT);
                viewSet.connect(tmpButton.getId(), ConstraintSet.TOP, invisibleButtons[i-1][j].getId(),ConstraintSet.BOTTOM);
                invisibleButtons[i][j] = tmpButton;
                tmpButton = null;
            }
        }
        for(int i = 0; i < row; i++){
            for(int j = 0; j < col; j++){
                viewSet.setVisibility(invisibleButtons[i][j].getId(), ConstraintSet.INVISIBLE);
            }
        }
    }

    private void startTimer(final TextView timeView){
        final Handler handler = new Handler();
        timer = new Timer();
        startTime = System.currentTimeMillis();

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        now = System.currentTimeMillis();
                        milliSecond = passedTime + (now - startTime);
                        double time = milliSecond / 1000.0;
                        timeView.setText(String.format("%.3f%s",time,"sec."));
                    }
                });
            }
        },0,90);


    }






}
