package com.tomas.pcs_asi;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

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

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.pcs_asi.ListData.Get_Item_BOM;
import com.tomas.pcs_asi.ListData.Get_Machine;
import com.tomas.pcs_asi.ListData.User_Lists;
import com.tomas.pcs_asi.lib.KeyMapping;
import com.tomas.pcs_asi.lib.ProductionSchedule;
import com.tomas.pcs_asi.lib.Settings;
import com.tomas.pcs_asi.lib.common.AsyncHttpClient;
import com.tomas.pcs_asi.lib.common.Scanner;
import com.tomas.pcs_asi.lib.common.Utils;

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

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class Ins_Start_Activity extends Scanner implements View.OnClickListener {
    TextView txt_message, txt_header, txt_ics, txt_lot_no, txt_job_order, txt_check_time, txt_mag_no, txt_machine, txt_user, txt_overdue_title,
            txt_overdue_dt;
    String str_process, str_status, str_overdue_dt, str_overdue_title, str_sch_id, str_ics, str_job, str_lot, str_check_time, str_mag_no,
            machine_type, dt_to_server, str_input,str_item_type;
    ConstraintLayout layout_alert, layout_alert_plan;
    LinearLayout layout_process, layout_mag_no;
    boolean Overdue, b_confirm;
    Calendar calendar;
    SimpleDateFormat fm_dt_server;
    Button btn_start;
    Map<String, Get_Machine> map_machine;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ins_start);
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);
        fm_dt_server = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        b_confirm = true;
//        map_machine = new LinkedHashMap<>();

        layout_alert = (ConstraintLayout)findViewById(R.id.layout_alert);
        layout_alert_plan = (ConstraintLayout) findViewById(R.id.layout_alert_plan);
        layout_process = (LinearLayout)findViewById(R.id.layout_process);
        layout_mag_no = (LinearLayout)findViewById(R.id.layout_mag_no);

        btn_start = (Button)findViewById(R.id.btn_start);
        txt_header = (TextView) findViewById(R.id.txt_header);
        txt_ics = (TextView) findViewById(R.id.txt_ics);
        txt_job_order = (TextView) findViewById(R.id.txt_job_order);
        txt_lot_no = (TextView) findViewById(R.id.txt_lot_no);
        txt_check_time = (TextView) findViewById(R.id.txt_check_time);
        txt_mag_no = (TextView) findViewById(R.id.txt_mag_no);
        txt_machine = (TextView) findViewById(R.id.txt_machine);
        txt_user = (TextView) findViewById(R.id.txt_user);
        txt_message = (TextView)findViewById(R.id.txt_message);
        txt_overdue_title = (TextView) findViewById(R.id.txt_overdue_title);
        txt_overdue_dt = (TextView) findViewById(R.id.txt_overdue_dt);

        str_process = Settings.getPROCESS();
        str_status  = Settings.getSTATUS();
        str_overdue_dt  = Settings.getOverdueDt();
        str_overdue_title = Settings.getOverdueTitle();
        str_sch_id = Settings.getSchId();
        str_ics = Settings.getICS();
        str_job = Settings.getJobOrder();
        str_lot = Settings.getLotNo();
        str_check_time = Settings.getCheckTime();
        str_mag_no = Settings.getMagNo();
        machine_type = Settings.getMcType();
        str_item_type = Settings.getItemType();
        str_input = Settings.getQtyInput();
        Log.d(getString(R.string.tag), "Ins start Activity : " + str_process+" | "+ str_status+ " | "+str_overdue_dt+"|"+str_mag_no+"|"+str_item_type);
        Log.d(getString(R.string.tag), "machine_type : " + machine_type);

        txt_header.setText(str_process);
        txt_ics.setText("ICS : "+str_ics);
        txt_job_order.setText("JOB ORDER : "+str_job);
        txt_lot_no.setText("LOT NO : "+str_lot);
        txt_check_time.setText(str_check_time);


        if (str_overdue_dt.trim().equals("")||str_overdue_dt.trim().equals("null")){
            Overdue = false;
            layout_alert_plan.setVisibility(View.GONE);
            layout_process.setVisibility(View.VISIBLE);

        }else{
            Overdue = true;
            layout_process.setVisibility(View.GONE);
            layout_alert_plan.setVisibility(View.VISIBLE);
            txt_overdue_title.setText(str_overdue_title);
            txt_overdue_dt.setText(str_overdue_dt);
        }

        if (str_process.trim().equals(ProductionSchedule.PROCESS.APPEARANCE.toString())){
            layout_mag_no.setVisibility(View.GONE);
        }else {
            //BONDING_INS : load machine now.
            Get_Machine(machine_type, str_item_type, "");
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_ok:
                Overdue = false;
                layout_alert_plan.setVisibility(View.GONE);
                layout_process.setVisibility(View.VISIBLE);
                break;

            case R.id.imb_back:
                Intent intent = new Intent(Ins_Start_Activity.this, Search_ProcessSheet_Activity.class);
                startActivity(intent);
                finish();
                break;

            case R.id.btn_start:
                if (b_confirm == true) {
                    Block_button();
                    if (str_process.trim().equals(ProductionSchedule.PROCESS.BONDING_INS.toString())) {
                        Update_BD_Ins();
                    } else {//Appearance
                        Update_APP_Ins();
                    }
                }
                break;

            case R.id.btn_clear:
                Clear_Text();
                break;
        }
    }
    private void Block_button() {
        b_confirm = false;
        btn_start.setEnabled(false);
        btn_start.setBackgroundResource(R.drawable.button_backgroup_gray);
    }

    private void Unblock_button() {
        b_confirm = true;
        btn_start.setEnabled(true);
        btn_start.setBackgroundResource(R.drawable.button_backgroup_green);
    }
    private void Clear_Text() {
        txt_user.setText("");
        txt_machine.setText("");
        txt_mag_no.setText("");

    }

    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
        if (data.trim().equals(""))
            return;

        try {
            Log.d(getString(R.string.tag), "scan data : " + data);
            String str_scan = data.trim();

            Log.d(getString(R.string.tag), "scan data : " + data.trim().substring(0,2));

            if (str_scan.contains(machine_type)) {//sacn machine
                if (str_process.trim().equals(ProductionSchedule.PROCESS.BONDING_INS.toString())) {//BONDING_INS check machine from list
                    if (map_machine.containsKey(str_scan)) {
                        txt_machine.setText(str_scan);
                    } else {
                        new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("ไม่พบเครื่องจักร")
                                .show();
                    }
                }else {//APPEARANCE : load machine list after scan machine
                    Get_Machine(machine_type, str_item_type, str_scan.trim());
                }
            } else if (str_scan.length() == 6) {//user
                Check_User(str_scan);

            } else if (str_scan.length() == 4){
                if (str_process.trim().equals(ProductionSchedule.PROCESS.BONDING_INS.toString())) {
                    if (str_scan.trim().equals(str_mag_no)) {
                        txt_mag_no.setText(str_scan);

                    } else {
                        new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("..........Mag No. ไม่ตรงกัน  !.......... "+" Mag No. = "+str_mag_no)
                                .show();
                    }
                }else{
                    new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("QR code ไม่ถูกต้อง!")
                            .show();
                }
            }else{
                new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("QR code ไม่ถูกต้อง!")
                        .show();
            }
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);
        } catch (Exception e) {
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
        }
    }



    private void Update_APP_Ins() {
        if (txt_user.getText().toString().equals("")){
            Unblock_button();
            new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณากรอกข้อมูลให้ครบ!")
                    .show();
        }else{
            if (str_check_time.trim().equals("1")) {//update start_dt --> productionplan เฉพาะครั้งแรกเท่านั้น
                calendar = Calendar.getInstance();
                calendar = (Calendar) calendar.clone();
                dt_to_server = fm_dt_server.format(calendar.getTime());
                Log.d(getString(R.string.tag), "dt_to_server : " + dt_to_server);
            }else{
                dt_to_server = "";
            }
            try {
                layout_alert.setVisibility(View.VISIBLE);
                txt_message.setText("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

                JSONObject json = new JSONObject();
                json.put("cmd", "update_app_working");
                json.put("check_time", txt_check_time.getText().toString().trim());
                json.put("act_dt", dt_to_server);
                json.put("sch_id", str_sch_id);

                new AsyncHttpClient(getApplicationContext(),
                        Settings.getMgmtList().get("web_api") + "/production_plan.php",
                        json.toString()) {
                    @Override
                    protected void onFinished(String response, int resp_code) {
                        Log.d(getString(R.string.tag), "response: " + response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String status = jsonObject.getString("status");
                            int affected_rows = jsonObject.getInt("affected_rows");
                            if (status.equals("success") && affected_rows > 0) {
                                Insert_EventINS();

                            } else {
                                layout_alert.setVisibility(View.GONE);
                                new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR")
                                        .setContentText("Can't update ProductionPlan")
                                        .show();
                            }
                        } catch (JSONException e) {
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(e.getMessage())
                                    .show();
                        }
                    }
                }.execute();
            } catch (Exception e) {
                layout_alert.setVisibility(View.GONE);
                new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
        }
    }

    private void Update_BD_Ins() {
        if (txt_mag_no.getText().toString().equals("") || txt_user.getText().toString().equals("")){
            Unblock_button();
            new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Please complete the information!")
                    .show();
        }else{
            Block_button();

            if (str_check_time.trim().equals("1")) {//update start_dt --> productionplan เฉพาะครั้งแรกเท่านั้น
                calendar = Calendar.getInstance();
                calendar = (Calendar) calendar.clone();
                dt_to_server = fm_dt_server.format(calendar.getTime());
                Log.d(getString(R.string.tag), "dt_to_server : " + dt_to_server);
            }else{
                dt_to_server = "";
            }

            try {
                layout_alert.setVisibility(View.VISIBLE);
                txt_message.setText("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

                JSONObject json = new JSONObject();
                json.put("cmd", "update_bd_ins_working");
                json.put("check_time", txt_check_time.getText().toString().trim());
                json.put("act_dt", dt_to_server);
                json.put("sch_id", str_sch_id);

                new AsyncHttpClient(getApplicationContext(),
                        Settings.getMgmtList().get("web_api") + "/production_plan.php",
                        json.toString()) {
                    @Override
                    protected void onFinished(String response, int resp_code) {
                        Log.d(getString(R.string.tag), "response: " + response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String status = jsonObject.getString("status");
                            int affected_rows = jsonObject.getInt("affected_rows");
                            if (status.equals("success") && affected_rows > 0) {
                                Insert_EventINS();

                            } else {
                                Unblock_button();
                                layout_alert.setVisibility(View.GONE);
                                new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR")
                                        .setContentText("Can't update ProductionPlan")
                                        .show();
                            }
                        } catch (JSONException e) {
                            Unblock_button();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(e.getMessage())
                                    .show();
                        }
                    }
                }.execute();
            } catch (Exception e) {
                Unblock_button();
                layout_alert.setVisibility(View.GONE);
                new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
        }
    }

    private void Insert_EventINS() {
        Block_button();

        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        dt_to_server = fm_dt_server.format(calendar.getTime());
        Log.d(getString(R.string.tag), "dt_to_server : " + dt_to_server);

        if (str_process.trim().equals(ProductionSchedule.PROCESS.BONDING_INS.toString())){
            str_mag_no = txt_mag_no.getText().toString().trim();
        }else{//app
            str_mag_no = "";
        }
        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

            JSONObject json = new JSONObject();
            json.put("cmd", "add");
            JSONArray jsonArray = new JSONArray();

                Map<String, String> jsonParams = new HashMap<>();
                jsonParams.put("sch_id", str_sch_id);
                jsonParams.put("process", str_process);
                jsonParams.put("check_times", str_check_time);
                jsonParams.put("mag_no_input", str_mag_no);
                jsonParams.put("mag_no_output", "");
                jsonParams.put("input", str_input);
                jsonParams.put("output", "");
                jsonParams.put("machine_code", txt_machine.getText().toString().trim());
                jsonParams.put("start_user_id", txt_user.getText().toString().trim());
                jsonParams.put("start_dt", dt_to_server);
                JSONObject jsonObj = new JSONObject(jsonParams);
                jsonArray.put(jsonObj);

            json.put("ins_datas",jsonArray);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/event_ins.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");
                        if (status.equals("success") && affected_rows > 0) {
                            Toast.makeText(Ins_Start_Activity.this,R.string.insert,Toast.LENGTH_SHORT).show();
//                            Intent intent = new Intent(Ins_Start_Activity.this, Search_ProcessSheet_Activity.class);
//                            startActivity(intent);
                            finish();

                        } else {
                            layout_alert.setVisibility(View.GONE);
                            Unblock_button();
                            new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Can't insert EvenINS")
                                    .show();
                        }
                    } catch (JSONException e) {
                        Unblock_button();
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        } catch (Exception e) {
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Check_User(String data) {
        if (Settings.getMap_user().containsKey(data)){
            if (str_process.trim().equals(ProductionSchedule.PROCESS.BONDING_INS.toString())
                    && Settings.getMap_user().get(data).getBonding_ins().trim().equals("1")) {
                txt_user.setText(data);

            }else if (str_process.trim().equals(ProductionSchedule.PROCESS.APPEARANCE.toString())
                    && Settings.getMap_user().get(data).getAppearance().trim().equals("1")) {
                txt_user.setText(data);

            }else {
                txt_user.setText("");
                new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("ไม่อนุญาตให้ทำงานใน "+str_process)
                        .show();
            }

        }else {
            txt_user.setText("");
            new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("ไม่พบรหัสพนักงาน!")//OK
                    .show();
        }
    }

    private void Get_Machine(String unit, String type, String str_scan_mc) {
        map_machine.clear();
        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");

            JSONObject json = new JSONObject();
            json.put("cmd", "get_machine");
            json.put("unit", unit);
            json.put("type", type);

            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), "response: " + response);

                    try {
                        JSONArray jArray = new JSONArray(response);

                        if (jArray.length() == 0){
                            layout_alert.setVisibility(View.GONE);
                            SweetAlertDialog d = new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.WARNING_TYPE);
                            d.setCancelable(false);
                            d.setTitleText("แจ้งเตือน");
                            d.setContentText("ไม่พบเครื่องจักร : "+unit+"/"+type +"  \n กรุณาแจ้ง leader");
                            d.setConfirmText("รับทราบ");
                            d.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismiss();
                                    finish();
                                }
                            });
                            d.show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                map_machine.put(jArray.getJSONObject(i).getString("Code").trim(),
                                        new Get_Machine(
                                                jArray.getJSONObject(i).getString("Code").trim(),
                                                jArray.getJSONObject(i).getString("Type").trim(),
                                                jArray.getJSONObject(i).getString("Frequency").trim() == "null" ? "0" : jArray.getJSONObject(i).getString("Frequency").trim(),
                                                jArray.getJSONObject(i).getString("Max_line_SP").trim() == "null" ? "0" : jArray.getJSONObject(i).getString("Max_line_SP").trim(),
                                                jArray.getJSONObject(i).getString("Cavity").trim() == "null" ? "0" : jArray.getJSONObject(i).getString("Cavity").trim()));
                            }
                            layout_alert.setVisibility(View.GONE);

                            if (str_process.trim().equals(ProductionSchedule.PROCESS.APPEARANCE.toString())) {//BONDING_INS check machine from list
                                if (map_machine.containsKey(str_scan_mc)) {
                                    txt_machine.setText(str_scan_mc);
                                } else {
                                    txt_machine.setText("");
                                    new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                            .setTitleText("แจ้งเตือน")
                                            .setContentText("ไม่พบเครื่องจักร")
                                            .show();
                                }
                            }

                        }
                        Log.d(getString(R.string.tag), String.valueOf(map_machine.size()));
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Ins_Start_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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


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

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode >= KeyMapping.P1.getId()
                && keyCode <= KeyMapping.P4.getId())
        {
            switch (KeyMapping.fromId(keyCode)) {
                case P1:
                    Intent intent = new Intent(Ins_Start_Activity.this, Search_ProcessSheet_Activity.class);
                    startActivity(intent);
                    finish();
                    break;

                case P2:
                    if (Overdue == true){
                        Overdue = false;
                        layout_alert_plan.setVisibility(View.GONE);
                        layout_process.setVisibility(View.VISIBLE);

                    }else {
                        if (b_confirm == true) {
                            Block_button();
                            if (str_process.trim().equals(ProductionSchedule.PROCESS.BONDING_INS.toString())) {
                                Update_BD_Ins();
                            } else {//Appearance
                                Update_APP_Ins();
                            }
                        }
                    }
                    break;

                case P3:
                    Clear_Text();
                    break;
            }
        }
        return super.onKeyUp(keyCode, event);
    }
}