package com.tomas.pcs_asi;

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.EditText;
import android.widget.TextView;

import com.keyence.autoid.sdk.scan.DecodeResult;
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 cn.pedant.SweetAlert.SweetAlertDialog;

public class Search_ProcessSheet_Activity extends Scanner implements View.OnClickListener {
    TextView txt_header, txt_ics, txt_job_order, txt_message;
    ConstraintLayout layout_alert_save;
    String str_process, PROCESS, STATUS, PLASMA, ICS, JOB_ORDER, ITEM_TYPE;
    int scan = 0, diebond_process = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_process_sheet);
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);

        layout_alert_save = (ConstraintLayout)findViewById(R.id.layout_alert_save);
        txt_message = (TextView)findViewById(R.id.txt_message);

        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);

        str_process = Settings.getPROCESS();
        txt_header.setText(str_process);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imb_back:
                finish();
                break;

            case R.id.btn_clear:
                Clear_textview();
                break;
        }
    }

    @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);

            if (scan == 0){
                if (!data.trim().equals("")) {
                    scan = 1;
                    txt_ics.setText(data.trim());
                    txt_job_order.setText("");
                }

            }else{
                if (!data.trim().equals("")) {
                    txt_job_order.setText(data.trim());
                    scan = 0;

                    Check_ProcessSheet();
                }
            }

            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

        } catch (Exception e) {
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
        }
    }

    private void Check_ProcessSheet() {
        try {
            layout_alert_save.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");

            JSONObject json = new JSONObject();
            json.put("cmd", "check_process_sheet");
            json.put("ics_product", txt_ics.getText().toString().trim());
            json.put("job_order", txt_job_order.getText().toString().trim());

            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 {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0) {
                            Clear_textview();
                            layout_alert_save.setVisibility(View.GONE);
                            SweetAlertDialog pDialog = new SweetAlertDialog(Search_ProcessSheet_Activity.this, SweetAlertDialog.WARNING_TYPE);
                            pDialog.setTitleText("แจ้งเตือน");
                            pDialog.setContentText("ไม่พบ Process Sheet!");
                            pDialog.setCancelable(false);
                            pDialog.show();
                        } else {
                            for (int i = 0; i < jArray.length(); i++) {
                                PROCESS = jArray.getJSONObject(i).getString("process").trim();
                                STATUS = jArray.getJSONObject(i).getString("status").trim();
                                ICS = jArray.getJSONObject(i).getString("ICSProductCode").trim();
                                JOB_ORDER = jArray.getJSONObject(i).getString("job_order").trim();
                                ITEM_TYPE = jArray.getJSONObject(i).getString("type").trim() == "null" ? "" : jArray.getJSONObject(i).getString("type").trim();
                                PLASMA = jArray.getJSONObject(i).getString("plasma").trim() == "null" ? "" : jArray.getJSONObject(i).getString("plasma").trim();
                                diebond_process = jArray.getJSONObject(i).getInt("diebond_process");
                            }
                            Log.d(getString(R.string.tag), "response: " + PROCESS + "/" + STATUS);
                            Check_Process();
                            layout_alert_save.setVisibility(View.GONE);
                        }
                    } catch (JSONException e) {
                        layout_alert_save.setVisibility(View.GONE);
                        new SweetAlertDialog(Search_ProcessSheet_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void Check_Process() {
        Clear_textview();
        Discard_Scanner();
        Settings.setICS(ICS);
        Settings.setJobOrder(JOB_ORDER);
        Settings.setItemType(ITEM_TYPE);

        if (str_process.trim().equals(ProductionSchedule.PROCESS.DIE_BOND.toString())){
            Settings.setDbProcessTimes(diebond_process);
            Intent intent = new Intent(Search_ProcessSheet_Activity.this, DB_Lot_Activity.class);
            startActivity(intent);
            finish();

        } else if (str_process.trim().equals(ProductionSchedule.PROCESS.WIRE_BOND.toString())){//menu wire bond

                if (PLASMA.trim().equals(ProductionSchedule.STATUS.PLASMA.toString())){//PLASMA
                    Settings.setMcType(ProductionSchedule.MACHINE.PLASMA.toString());
                    Intent intent = new Intent(Search_ProcessSheet_Activity.this, Plasma_Lot_Activity.class);
                    startActivity(intent);
                    finish();

                }else{// NO PLASMA
                    Settings.setMcType(ProductionSchedule.MACHINE.WB.toString());
                    Intent intent = new Intent(Search_ProcessSheet_Activity.this, WB_Lot_Activity.class);
                    startActivity(intent);
                    finish();
                }

        }else if (str_process.trim().equals(ProductionSchedule.PROCESS.BONDING_INS.toString())){
            Log.d(getString(R.string.tag), "MENU:BONDING_INS " + PROCESS + "/" + STATUS);
            Settings.setMcType(ProductionSchedule.MACHINE.DB_INS.toString());

            Intent intent = new Intent(Search_ProcessSheet_Activity.this, Ins_Lot_Activity.class);
            startActivity(intent);
            finish();

        }else if (str_process.trim().equals(ProductionSchedule.PROCESS.MOLD.toString())) {
            Log.d(getString(R.string.tag), "MENU:MOLD " + PROCESS + "/" + STATUS);
            Settings.setMcType(ProductionSchedule.MACHINE.MOLD.toString());

            Intent intent = new Intent(Search_ProcessSheet_Activity.this, Mold_Lot_Activity.class);
            startActivity(intent);
            finish();
        }else if (str_process.trim().equals(ProductionSchedule.PROCESS.APPEARANCE.toString())){
            Log.d(getString(R.string.tag), "MENU:APPEARANCE " + PROCESS + "/" + STATUS);
            Settings.setMcType(ProductionSchedule.MACHINE.APP_INS.toString());

            Intent intent = new Intent(Search_ProcessSheet_Activity.this, Ins_Lot_Activity.class);
            startActivity(intent);
            finish();

        }else{
            Log.d(getString(R.string.tag), "MENU:else " + PROCESS + "/" + STATUS);
        }

    }

    private void Discard_Scanner() {
        // Discard the ScanManager class instance.
        mScanManager.removeDataListener(Search_ProcessSheet_Activity.this);
        // Discard the ScanManager class instance to release the resources.
        mScanManager.releaseScanManager();

    }

    private void Clear_textview() {
        scan = 0;
        txt_ics.setText("");
        txt_job_order.setText("");
    }

    @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:
                    finish();
                    break;

                case P2:
                    Clear_textview();
                    break;
            }
        }

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