package com.webclip.base;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.TextViewCompat;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.webclip.base.databinding.ActivityMainBinding;

import org.w3c.dom.Text;

import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainJSQActivity extends AppCompatActivity {
    ActivityMainBinding activityMainBinding;
    private StringBuilder currentInput=new StringBuilder("");
    private BigDecimal currentAnswer=new BigDecimal(0);
    private boolean hasCount=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setNavigationBarColor(getColor(R.color.white));

        super.onCreate(savedInstanceState);
        View decor = getWindow().getDecorView();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        activityMainBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(activityMainBinding.getRoot());

        if(TextUtils.isEmpty(getString(MainJSQActivity.this,"loc_pass",""))){
            startActivity(new Intent(this,StartActivity.class));
            finish();
            return;
        }
        setListener();
        TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(activityMainBinding.inputText, 10, 50, 2, TypedValue.COMPLEX_UNIT_SP);
        TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(activityMainBinding.outputText, 10, 50, 2, TypedValue.COMPLEX_UNIT_SP);
    }

    public void setListener(){
        activityMainBinding.btn0.setOnClickListener(view -> addInput("0"));
        activityMainBinding.btn1.setOnClickListener(view -> addInput("1"));
        activityMainBinding.btn2.setOnClickListener(view -> addInput("2"));
        activityMainBinding.btn3.setOnClickListener(view -> addInput("3"));
        activityMainBinding.btn4.setOnClickListener(view -> addInput("4"));
        activityMainBinding.btn5.setOnClickListener(view -> addInput("5"));
        activityMainBinding.btn6.setOnClickListener(view -> addInput("6"));
        activityMainBinding.btn7.setOnClickListener(view -> addInput("7"));
        activityMainBinding.btn8.setOnClickListener(view -> addInput("8"));
        activityMainBinding.btn9.setOnClickListener(view -> addInput("9"));
        activityMainBinding.btnPoint.setOnClickListener(view -> addInput("."));
        activityMainBinding.btnAdd.setOnClickListener(view -> addInput("+"));
        activityMainBinding.btnSubtract.setOnClickListener(view -> addInput("-"));
        activityMainBinding.btnMultiply.setOnClickListener(view -> addInput("*"));
        activityMainBinding.btnDivide.setOnClickListener(view -> addInput("/"));
        activityMainBinding.btnBackspace.setOnClickListener(view -> {
            if(currentInput.length()>0){
                currentInput.deleteCharAt(currentInput.length()-1);
            }
            displayInput();
        });
        activityMainBinding.btnClear.setOnClickListener(view -> {
            currentInput=new StringBuilder("");
            displayInput();
            activityMainBinding.outputText.setText("");
        });
        activityMainBinding.btnEqual.setOnClickListener(view -> {
            StringBuilder result = compute(currentInput);
            displayAnswer(result);
            hasCount=true;
        });
    }

    Handler handler = new Handler();
    public void displayInput(){
        activityMainBinding.inputText.setText(currentInput);
        if(currentInput.toString().equals(MainActivity.getString(MainJSQActivity.this,"loc_pass",""))){
            toNextActivity();
        }
    }

    private void toNextActivity() {
        handler.postDelayed(() -> {
            startActivity(new Intent(MainJSQActivity.this,IndexActivity.class));
        }, 1000);
    }

    public void displayAnswer(StringBuilder string){
        Pattern compile = Pattern.compile( "[^0-9.-]");
        StringBuilder result = new StringBuilder(compile.matcher(string).replaceAll(""));
        if(result.charAt(result.length()-1)=='-'){
            System.out.println(result.charAt(result.length()-1));
            result.deleteCharAt(result.length()-1);
        }
        System.out.println(result);
        activityMainBinding.outputText.setText(result);
    }

    public StringBuilder compute(StringBuilder str){
        Pattern pattern = Pattern.compile("([\\d.]+)\\s*([*/])\\s*([\\d.]+)");
        Matcher matcher=pattern.matcher(str.toString());
        while(matcher.find()){
            BigDecimal first = BigDecimal.valueOf(Double.valueOf(matcher.group(1)));
            BigDecimal second = BigDecimal.valueOf(Double.valueOf(matcher.group(3)));
            switch (matcher.group(2)){
                case "*":
                    first=first.multiply(second);
                    break;
                case "/":
                    first=first.divide(second);
                    break;
            }
            str.replace(matcher.start(),matcher.end(),first.toString());
            matcher.reset(str.toString());
        }

        pattern = Pattern.compile("([\\d.]+)\\s*([+-])\\s*([\\d.]+)");
        matcher=pattern.matcher(str.toString());
        while (matcher.find()){
            BigDecimal first = BigDecimal.valueOf(Double.valueOf(matcher.group(1)));
            BigDecimal second = BigDecimal.valueOf(Double.valueOf(matcher.group(3)));
            switch(matcher.group(2)){
                case "+":
                    first=first.add(second);
                    break;
                case "-":
                    first=first.subtract(second);
                    break;

            }
            str.replace(matcher.start(),matcher.end(),first.toString());
            matcher.reset(str.toString());
        }
        return str;
    }
    public void addInput(String string){
        if(hasCount==false){
            currentInput.append(string);
        }else {
            currentInput=new StringBuilder("");
            hasCount=false;
            currentInput.append(string);
        }
        displayInput();
    }


    public static void saveString(Context context,String key, String value) {
        SharedPreferences sp = context.getSharedPreferences("InitApp", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(key, value);
        editor.apply();
    }

    public static String getString(Context context,String key, String defValue) {
        if (context == null) {
            return defValue;
        }
        SharedPreferences sp = context.getSharedPreferences("InitApp", Activity.MODE_PRIVATE);
        return sp.getString(key, defValue);
    }


    public static void saveBoolean(Context context,String key, Boolean value) {
        SharedPreferences sp = context.getSharedPreferences("InitApp", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean(key, value);
        editor.apply();
    }

    public static Boolean getBoolean(Context context,String key, Boolean defValue) {
        if (context == null) {
            return defValue;
        }
        SharedPreferences sp = context.getSharedPreferences("InitApp", Activity.MODE_PRIVATE);
        return sp.getBoolean(key, defValue);
    }

}