package com.iq.intelligence.study;


import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class GameMainActivity extends AppCompatActivity {

    private ProgressBar progressBar;
    private CountDownTimer myTimer;
    private int levelNumber;
    private TextView questionText, textQuestionNumber;
    private Button answer1, answer2, answer3, answer4;

    private GameQuestions questionManager;
    private String theCorrectAnswer;
    private int questionNumber = 1;
    private SharedPreferences prefs;
    private SharedPreferences.Editor editor;
//    private ImageView help;
    private int gemsCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_game);
        questionText = findViewById(R.id.QuestionText);
        textQuestionNumber = findViewById(R.id.text_QuestionNumber);
        answer1 = findViewById(R.id.Answer1_Btn);
        answer2 = findViewById(R.id.Answer2_Btn);
        answer3 = findViewById(R.id.Answer3_Btn);
        answer4 = findViewById(R.id.Answer4_Btn);

        progressBar = findViewById(R.id.timer_progressBar);

        Bundle bundle = getIntent().getExtras();
        levelNumber = bundle.getInt(PrescribedValue.LEVELS_NUMBER);
        questionNumber = (levelNumber-1)*5+questionNumber;
        getNextQuestion();


        prefs = getSharedPreferences(PrescribedValue.PRE_FILE, Context.MODE_PRIVATE);
        editor = prefs.edit();

        answer1.setOnClickListener(v -> {
            if (answer1.getText().toString().equals(theCorrectAnswer)) {
                myTimer.cancel();
                delayNextQuestion();
                correctAnswer(answer1);

            } else {
                myTimer.cancel();
                wrongAnswer(answer1);
                delayExit();
            }
        });

        answer2.setOnClickListener(v -> {
            if (answer2.getText().toString().equals(theCorrectAnswer)) {
                myTimer.cancel();
                delayNextQuestion();
                correctAnswer(answer2);

            } else {
                myTimer.cancel();
                wrongAnswer(answer2);
                delayExit();
            }
        });

        answer3.setOnClickListener(v -> {
            if (answer3.getText().toString().equals(theCorrectAnswer)) {
                myTimer.cancel();
                delayNextQuestion();
                correctAnswer(answer3);

            } else {
                myTimer.cancel();
                wrongAnswer(answer3);
                delayExit();
            }
        });

        answer4.setOnClickListener(v -> {
            if (answer4.getText().toString().equals(theCorrectAnswer)) {
                myTimer.cancel();
                delayNextQuestion();
                correctAnswer(answer4);

            } else {
                myTimer.cancel();
                wrongAnswer(answer4);
                delayExit();
            }
        });




        setProgressBar();
    }



    private void setHelperCount() {
        gemsCount = gemsCount - 1;
        prefs = getSharedPreferences("prefGem", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("gems", gemsCount);
        getHelpAnswer(questionNumber);
        editor.apply();
    }

    private void setProgressBar() {
        myTimer = new CountDownTimer(30000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                long time = millisUntilFinished / 1000;
                progressBar.setProgress(Integer.parseInt((String.valueOf(time))));

            }

            @Override
            public void onFinish() {
                myTimer.cancel();
                showDialogTimeOut();
            }
        }.start();
    }

    @SuppressLint({"SetTextI18n", "UseCompatLoadingForDrawables"})
    private void getNextQuestion() {
        getQuestionNumbers(questionNumber);

        answer1.setBackground(getDrawable(R.drawable.data_background));
        answer2.setBackground(getDrawable(R.drawable.data_background));
        answer3.setBackground(getDrawable(R.drawable.data_background));
        answer4.setBackground(getDrawable(R.drawable.data_background));

        textQuestionNumber.setText(getString(R.string.text_question) + " " + questionNumber);
    }


    private void getQuestionNumbers(int num) {
        String[] theQuestion = questionManager.getQuestions(num);
        questionText.setText(theQuestion[0]);
        answer1.setText(theQuestion[1]);
        answer2.setText(theQuestion[2]);
        answer3.setText(theQuestion[3]);
        answer4.setText(theQuestion[4]);
        theCorrectAnswer = theQuestion[5];



    }


    private void getHelpAnswer(int num) {
        String[] theQuestion = questionManager.getQuestions(num);
        theCorrectAnswer = theQuestion[5];
        Toast.makeText(this, theCorrectAnswer.toString(), Toast.LENGTH_LONG).show();

    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private void correctAnswer(Button button) {
        button.setBackground(getDrawable(R.drawable.right_bg));
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private void wrongAnswer(Button button) {
        button.setBackground(getDrawable(R.drawable.wrong_background));
    }

    private void delayExit() {
        myTimer.cancel();
        disableClickButton();

        if (answer1.getText().toString().equals(theCorrectAnswer)) {
            correctAnswer(answer1);
        }
        if (answer2.getText().toString().equals(theCorrectAnswer)) {
            correctAnswer(answer2);
        }
        if (answer3.getText().toString().equals(theCorrectAnswer)) {
            correctAnswer(answer3);
        }
        if (answer4.getText().toString().equals(theCorrectAnswer)) {
            correctAnswer(answer4);
        }

        final Handler handler = new Handler();
        handler.postDelayed(() -> {
            showDialogLose();
        }, 1000);
    }

    private void delayNextQuestion() {
        int i = questionNumber % 5;
        if (i == 0) {
            QuestionNumberFinish(questionNumber);
            return;
        }
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                questionNumber++;
                getNextQuestion();
                enableClickButton();
                setProgressBar();
            }
        }, 1000);


    }

    private void disableClickButton() {
        answer1.setClickable(false);
        answer2.setClickable(false);
        answer3.setClickable(false);
        answer4.setClickable(false);
    }

    private void enableClickButton() {
        answer1.setClickable(true);
        answer2.setClickable(true);
        answer3.setClickable(true);
        answer4.setClickable(true);
    }

    private void showDialogTimeOut() {
        Dialog dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // before
        dialog.setContentView(R.layout.count_time_finish);
        dialog.setCancelable(false);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(dialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;

        dialog.findViewById(R.id.bt_play_again).setOnClickListener(v -> {
            dialog.dismiss();
            finish();
            Bundle bundle = new Bundle();
            bundle.putInt(PrescribedValue.LEVELS_NUMBER, levelNumber);
            Intent intent = new Intent(GameMainActivity.this, GameMainActivity.class);
            intent.putExtras(bundle);
            startActivity(intent);
        });

        dialog.findViewById(R.id.bt_close_icon).setOnClickListener(v -> {
            dialog.dismiss();
            finish();
        });

        dialog.findViewById(R.id.bt_close).setOnClickListener(v -> {
            dialog.dismiss();
            finish();
        });

        dialog.show();
        dialog.getWindow().setAttributes(lp);
    }

    private void showDialogLose() {
        Dialog dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // before
        dialog.setContentView(R.layout.lose_dialog);
        dialog.setCancelable(false);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(dialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;

        dialog.findViewById(R.id.bt_play_again).setOnClickListener(v -> {
            dialog.dismiss();
            finish();
            Bundle bundle = new Bundle();
            bundle.putInt(PrescribedValue.LEVELS_NUMBER, levelNumber);
            Intent intent = new Intent(GameMainActivity.this, GameMainActivity.class);
            intent.putExtras(bundle);
            startActivity(intent);
        });

        dialog.findViewById(R.id.bt_close_icon).setOnClickListener(v -> {
            dialog.dismiss();
            finish();
        });

        dialog.findViewById(R.id.bt_close).setOnClickListener(v -> {
            dialog.dismiss();
            finish();
        });

        dialog.show();
        dialog.getWindow().setAttributes(lp);
    }

    private void setDialogWon() {
        Dialog dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // before
        dialog.setContentView(R.layout.pass_dialog);
        dialog.setCancelable(false);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(dialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;

        dialog.findViewById(R.id.bt_play_again).setOnClickListener(v -> {
            finish();
            myTimer.cancel();
            levelNumber++;
            Bundle bundle = new Bundle();
            bundle.putInt(PrescribedValue.LEVELS_NUMBER, levelNumber);
            Intent intent = new Intent(GameMainActivity.this, GameMainActivity.class);
            intent.putExtras(bundle);
            startActivity(intent);
        });

        dialog.findViewById(R.id.bt_close_icon).setOnClickListener(v -> {
            dialog.dismiss();
            finish();
        });

        dialog.findViewById(R.id.bt_close).setOnClickListener(v -> {
            dialog.dismiss();
            finish();
        });

        dialog.show();
        dialog.getWindow().setAttributes(lp);
    }

    private void QuestionNumberFinish(int number) {
            int g = number / 6;
            String format = String.format(getString(R.string.LevelValue), String.valueOf(levelNumber + 1));
            Log.d("-----", "----------format=" + format + "---number=" + number);
            setDialogWon();
            editor.putBoolean(format, true);
            editor.apply();


    }



    @Override
    protected void onPause() {
        super.onPause();
        myTimer.cancel();
    }

    @Override
    public void onBackPressed() {
        myTimer.cancel();
        super.onBackPressed();
    }
}