package com.example.admin.mygame;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.Preference;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

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

        final Button startButton = (Button)findViewById(R.id.start_button);
        final TextView countView = (TextView)findViewById(R.id.count_view);
        countView.setTextSize(96+48);
        countView.setText("");



        final Context context = this;

        startButton.setOnClickListener(new View.OnClickListener(){
            Timer timer = new Timer();
            final Handler handler = new Handler();
            int count = 3;
            @Override
            public void onClick(View view) {
                startButton.setVisibility(View.INVISIBLE);
                final long countStartTime = System.currentTimeMillis();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                long now = System.currentTimeMillis();
                                int remainingTime = (int)(count - ((now - countStartTime)/1000));

                                if(remainingTime < 0){
                                    timer.cancel();
                                    Intent intent = new Intent(context, Main2Activity.class);
                                    startActivity(intent);
                                }else if(remainingTime == 0){
                                    countView.setText("GO!!!");
                                }else {
                                    countView.setText(String.valueOf(remainingTime));
                                }
                            }
                        });
                    }
                },0,100);

            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        TextView scoreView = (TextView)findViewById(R.id.score_view);
        scoreView.setText("");

        SharedPreferences preferences = getSharedPreferences("best_time", MODE_PRIVATE);
        double bestTime = preferences.getLong("time", 9999999);

        scoreView.setText(String.format("best time : %.3f",bestTime / 1000.0));
    }
}
