package com.tomas.lps_asi;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.tomas.lps_asi.ListData.User_Lists;
import com.tomas.lps_asi.lib.KeyMapping;
import com.tomas.lps_asi.lib.LabelType;
import com.tomas.lps_asi.lib.MyAlert;
import com.tomas.lps_asi.lib.Settings;
import com.tomas.lps_asi.lib.common.AsyncHttpClient;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedHashMap;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    ConstraintLayout layout_alert;
    TextView txt_message;
    private static int title_click = 0;
    Map<String, User_Lists> map_user;
    Map<String, String> map_machine;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        layout_alert = (ConstraintLayout)findViewById(R.id.layout_alert);
        txt_message = (TextView)findViewById(R.id.txt_message);

        map_user = new LinkedHashMap<>();
        map_machine = new LinkedHashMap<>();

        Settings.init(MainActivity.this);
        Log.d(getString(R.string.tag), "Setting");

        init();
        get_machine();
    }

    private void get_machine() {
        layout_alert.setVisibility(View.VISIBLE);
        txt_message.setText("กรุณารอสักครู่ กำลังดาว์นโหลดข้อมูล...");
        map_machine.clear();
            try {
                JSONObject json = new JSONObject();
                json.put("cmd", "get_machine_code");
                new AsyncHttpClient(getApplicationContext(),
                        Settings.getMgmtList().get("web_api") + "/machine_master.php",
                        json.toString()) {
                    @Override
                    protected void onFinished(String response, int resp_code) {
                        Log.d(getString(R.string.tag), "mc response: " + response);

                        try {
                            JSONArray jArray = new JSONArray(response);

                            for (int i = 0; i < jArray.length(); i++) {
                                map_machine.put(jArray.getJSONObject(i).getString("Machine_Code").trim(),
                                        jArray.getJSONObject(i).getString("Machine_Code").trim());

                            }

                            Settings.setMachineList(map_machine);
                            layout_alert.setVisibility(View.GONE);
                        } catch (JSONException e) {
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(MainActivity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(e.getMessage())
                                    .show();
                        }
                    }
                }.execute();

            } catch (JSONException e) {
                layout_alert.setVisibility(View.GONE);
                new SweetAlertDialog(MainActivity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
    }

    private void init() {
        layout_alert.setVisibility(View.VISIBLE);
        txt_message.setText("กรุณารอสักครู่ กำลังดาว์นโหลดข้อมูล...");

        // download user data from web
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            new AsyncHttpClient(getApplicationContext()
                    ,Settings.getMgmtList().get("web_api") + "/users.php"
                    , json.toString()
            ) {
                @Override
                public void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);
                    // update mapItems
                    try {
                        JSONArray jArray = new JSONArray(response);
                        Log.d(getString(R.string.tag), "response json length: " + jArray.length());
                        if (jArray.length() == 0){
                            MyAlert alert =  new MyAlert(MainActivity.this);
                            alert.setMessage("ไม่พบข้อมูล Users");
                            alert.show();
                            layout_alert.setVisibility(View.GONE);
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                map_user.put( jArray.getJSONObject(i).getString("Code").trim(),
                                        new User_Lists(
                                                jArray.getJSONObject(i).getString("Code").trim(),
                                                jArray.getJSONObject(i).getString("NameThai").trim(),
                                                jArray.getJSONObject(i).getString("NameEng").trim(),
                                                jArray.getJSONObject(i).getString("Role").trim(),
                                                jArray.getJSONObject(i).getString("Type").trim(),
                                                jArray.getJSONObject(i).getString("Taping").trim(),
                                                jArray.getJSONObject(i).getString("TapingCheck").trim()));

                            }

                            Settings.setMap_user(map_user);
                            Toast.makeText(getApplicationContext(), "User ID has been successfully loaded.!", Toast.LENGTH_LONG).show();
                            layout_alert.setVisibility(View.GONE);
                        }
                    } catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(MainActivity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }
                    .execute();
        } catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(MainActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }


    @Override
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.layout_title:
                if (++title_click == 7) {
                    title_click = 0;
                    Toast.makeText(getApplicationContext(), "Settings mode!", Toast.LENGTH_LONG).show();

                    // call Settings activity
                    Log.d(getString(R.string.tag), "start settings activity");
                    Intent intent = new Intent(MainActivity.this, Setting_Activity.class);
                    startActivity(intent);
//                    finish();
                }
                break;
            case R.id.btn_taping:
                Settings.setLabelType(String.valueOf(LabelType.TYPE.Taping_Label));
//                Intent intent = new Intent(MainActivity.this, TapingLabel_Activity.class);
                Intent intent = new Intent(MainActivity.this, NewTapingLabel_Activity.class);
                startActivity(intent);
                break;

            case R.id.btn_balance:
                Settings.setLabelType(String.valueOf(LabelType.TYPE.Balance_Label));
                Intent intent1 = new Intent(MainActivity.this, BalanceLabel_Activity.class);
                startActivity(intent1);
                break;

            case R.id.btn_change_model:
                Settings.setLabelType(String.valueOf(LabelType.TYPE.ChangeModel_Label));
                Intent intent2 = new Intent(MainActivity.this, ChangeModel_Activity.class);
                startActivity(intent2);
                break;

            case R.id.btn_defective:
                Settings.setLabelType(String.valueOf(LabelType.TYPE.Defective_Label));
                Intent intent3 = new Intent(MainActivity.this, DefectiveLabel_Activity.class);
                startActivity(intent3);
                break;

            case R.id.btn_expired:
                Settings.setLabelType(String.valueOf(LabelType.TYPE.Expired_Label));
                Intent intent4 = new Intent(MainActivity.this, ExpiredLabel_Activity.class);
                startActivity(intent4);
                break;

            case R.id.btn_clean:
                Intent intent5 = new Intent(MainActivity.this, Cleaning_Activity.class);
                startActivity(intent5);
                break;

            case R.id.btn_taping_check:
                Intent intent6 = new Intent(MainActivity.this, TapingCheck_Activity.class);
                startActivity(intent6);
                break;
            case R.id.btn_close:
                finishAffinity();
                System.exit(0);
                break;

        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode >= KeyMapping.P1.getId()
                && keyCode <= KeyMapping.P4.getId())
        {
            switch (KeyMapping.fromId(keyCode)) {
                case P1:
                    finishAffinity();
                    System.exit(0);
                    break;

            }
        }

        return super.onKeyUp(keyCode, event);
    }
}