package com.tomas.pcs_asi;

import static android.app.ProgressDialog.show;

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

import androidx.constraintlayout.widget.ConstraintLayout;

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 java.text.SimpleDateFormat;
import java.util.Calendar;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class Search_ProcessSheet_Lot_Activity extends Scanner implements View.OnClickListener {
    TextView txt_header, txt_ics, txt_job_order, txt_lot_no, txt_message;
    String str_process, PROCESS, STATUS, SCH_ID, ICS, JOB_ORDER, LOT_NO, OVEN_MOLD_ID, OVEN_ID, DICER_ID, DICER_USER, DICER_MC,ITEM_TYPE,

            CLS_MC, CLS_LOT, CLS_MAX;
    int scan = 0;
    SimpleDateFormat date_time_fm;
    ConstraintLayout layout_alert_save;
    LinearLayout layout_line_no;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_searchprocess_oven_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);

        layout_line_no = (LinearLayout)findViewById(R.id.layout_lot_no);

        scan = 0;
        date_time_fm = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");

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

        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("");
                    txt_lot_no.setText("");
                }

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

            }else {
                if (!data.trim().equals("")) {
                    scan = 0;
                    txt_lot_no.setText(data.trim());
                    if (txt_ics.getText().toString().trim().equals("")
                            || txt_job_order.getText().toString().trim().equals("")
                            || txt_lot_no.getText().toString().trim().equals("")) {

                        new SweetAlertDialog(Search_ProcessSheet_Lot_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("แจ้งเตือน")
                                .setContentText("กรุณากรอกข้อมูลให้ครบ!")
                                .show();
                    }else {
                        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());
                json.put("lot_no", txt_lot_no.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();
                                new SweetAlertDialog(Search_ProcessSheet_Lot_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("แจ้งเตือน")
                                        .setContentText("ไม่พบ Process Sheet!")
                                        .show();
                                layout_alert_save.setVisibility(View.GONE);
                            } else {
                                for (int i = 0; i < jArray.length(); i++) {
                                    PROCESS = jArray.getJSONObject(i).getString("process").trim();
                                    STATUS = jArray.getJSONObject(i).getString("status").trim();
                                    SCH_ID = jArray.getJSONObject(i).getString("sch_id").trim();
                                    ICS = jArray.getJSONObject(i).getString("ICSProductCode").trim();
                                    JOB_ORDER = jArray.getJSONObject(i).getString("job_order").trim();
                                    LOT_NO = jArray.getJSONObject(i).getString("lot_no").trim();
                                    OVEN_ID = jArray.getJSONObject(i).getString("oven_diebond_id").trim() == "null" ? "" : jArray.getJSONObject(i).getString("oven_diebond_id").trim();
                                    OVEN_MOLD_ID = jArray.getJSONObject(i).getString("oven_mold_id").trim() == "null" ? "" : jArray.getJSONObject(i).getString("oven_mold_id").trim();
                                    DICER_ID = jArray.getJSONObject(i).getString("dicer_id").trim() == "null" ? "" : jArray.getJSONObject(i).getString("dicer_id").trim();
                                    DICER_USER = jArray.getJSONObject(i).getString("dicer_start_user_id").trim() == "null" ? "" : jArray.getJSONObject(i).getString("dicer_start_user_id").trim();
                                    DICER_MC = jArray.getJSONObject(i).getString("dicer_machine").trim() == "null" ? "" : jArray.getJSONObject(i).getString("dicer_machine").trim();
                                    CLS_MC = jArray.getJSONObject(i).getString("classify_machine").trim() == "null" ? "" : jArray.getJSONObject(i).getString("classify_machine").trim();
                                    CLS_LOT  = jArray.getJSONObject(i).getString("classify_lot").trim() == "null" ? "" : jArray.getJSONObject(i).getString("classify_lot").trim();
                                    CLS_MAX = jArray.getJSONObject(i).getString("max_cls").trim() == "null" ? "" : jArray.getJSONObject(i).getString("max_cls").trim();
                                    ITEM_TYPE = jArray.getJSONObject(i).getString("type").trim() == "null" ? "" : jArray.getJSONObject(i).getString("type").trim();

                                }
                                Log.d(getString(R.string.tag), "response: " + PROCESS + "/" + STATUS);
                                Check_Process();
                                Clear_textview();
                                layout_alert_save.setVisibility(View.GONE);
                            }
                        } catch (JSONException e) {
                            layout_alert_save.setVisibility(View.GONE);
                            new SweetAlertDialog(Search_ProcessSheet_Lot_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_Lot_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
    }

    private void Check_Process() {
        Log.d(getString(R.string.tag), "Check_Process: " + PROCESS + "/" + str_process);

        if(str_process.trim().equals(PROCESS) && PROCESS.trim().equals(ProductionSchedule.PROCESS.OVEN_DIE_BOND.toString())) {//menu oven die bond
            if (STATUS.trim().equals(ProductionSchedule.STATUS.DIE_BOND_WAIT.toString()) ||
                STATUS.trim().equals(ProductionSchedule.STATUS.DIE_BOND_OVEN.toString())) {
                Settings.setSchId(SCH_ID);
                Settings.setICS(ICS);
                Settings.setJobOrder(JOB_ORDER);
                Settings.setLotNo(LOT_NO);
                Settings.setSTATUS(STATUS);
                Settings.setItemType(ITEM_TYPE);
                Settings.setMcType(ProductionSchedule.MACHINE.OVEN.toString());
                Settings.setOvenId(OVEN_ID);
                Intent_OVEN();

            } else if (STATUS.trim().equals(ProductionSchedule.STATUS.DIE_BOND_FINISHED.toString())) {
                new SweetAlertDialog(Search_ProcessSheet_Lot_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("สถานะ ProcessSheet : "+STATUS)
                        .show();
            }

        }else if (str_process.trim().equals(PROCESS) && PROCESS.trim().equals(ProductionSchedule.PROCESS.OVEN_MOLD.toString())){
            if (STATUS.trim().equals(ProductionSchedule.STATUS.MOLD_WAIT.toString()) ||
                STATUS.trim().equals(ProductionSchedule.STATUS.MOLD_OVEN.toString())){

                Settings.setSchId(SCH_ID);
                Settings.setICS(ICS);
                Settings.setJobOrder(JOB_ORDER);
                Settings.setLotNo(LOT_NO);
                Settings.setSTATUS(STATUS);
                Settings.setItemType(ITEM_TYPE);
                Settings.setMcType(ProductionSchedule.MACHINE.OVEN.toString());
                Settings.setOvenId(OVEN_MOLD_ID);
                Intent_OVEN();

            }else if (STATUS.trim().equals(ProductionSchedule.STATUS.MOLD_FINISHED.toString())) {
                new SweetAlertDialog(Search_ProcessSheet_Lot_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("สถานะ ProcessSheet : "+STATUS)
                        .show();
            }else{
                new SweetAlertDialog(Search_ProcessSheet_Lot_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("สถานะ ProcessSheet : "+STATUS)
                    .show();
            }
        }else  if (str_process.trim().equals(ProductionSchedule.PROCESS.DICER.toString())){
            if (STATUS.trim().equals(ProductionSchedule.STATUS.MOLD_FINISHED.toString())||
                STATUS.trim().equals(ProductionSchedule.STATUS.DICER_WORKING.toString())){
                Settings.setSchId(SCH_ID);
                Settings.setICS(ICS);
                Settings.setJobOrder(JOB_ORDER);
                Settings.setLotNo(LOT_NO);
                Settings.setSTATUS(STATUS);
                Settings.setItemType(ITEM_TYPE);
                Settings.setMcType(ProductionSchedule.MACHINE.DICER.toString());
                Settings.setDicerId(DICER_ID);
                Settings.setUserId(DICER_USER);
                Settings.setMACHINE(DICER_MC);

                // Discard the ScanManager class instance.
                mScanManager.removeDataListener(Search_ProcessSheet_Lot_Activity.this);
                // Discard the ScanManager class instance to release the resources.
                mScanManager.releaseScanManager();

                Check_Random_Status();


            }else if (STATUS.trim().equals(ProductionSchedule.STATUS.DICER_FINISHED.toString())){
                new SweetAlertDialog(Search_ProcessSheet_Lot_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("สถานะ ProcessSheet : "+STATUS)
                        .show();
            }else{
                new SweetAlertDialog(Search_ProcessSheet_Lot_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("สถานะ ProcessSheet : "+STATUS)
                        .show();
            }
        }else  if (str_process.trim().equals(ProductionSchedule.PROCESS.CLASSIFY.toString())){
            if (STATUS.trim().equals(ProductionSchedule.STATUS.APPEARANCE_FINISHED.toString())
                ||STATUS.trim().equals(ProductionSchedule.STATUS.DICER_FINISHED.toString())){
                Settings.setSchId(SCH_ID);
                Settings.setICS(ICS);
                Settings.setJobOrder(JOB_ORDER);
                Settings.setLotNo(LOT_NO);
                Settings.setSTATUS(STATUS);
                Settings.setClsMax(CLS_MAX);
                Settings.setItemType(ITEM_TYPE);
                Settings.setMcType(ProductionSchedule.MACHINE.CLS.toString());

                // Discard the ScanManager class instance.
                mScanManager.removeDataListener(Search_ProcessSheet_Lot_Activity.this);
                // Discard the ScanManager class instance to release the resources.
                mScanManager.releaseScanManager();

                Intent intent = new Intent(Search_ProcessSheet_Lot_Activity.this, Classify_Activity.class);
                startActivity(intent);
                finish();

            }else if (STATUS.trim().equals(ProductionSchedule.STATUS.CLASSIFY_WORKING.toString())){
                Settings.setSchId(SCH_ID);
                Settings.setICS(ICS);
                Settings.setJobOrder(JOB_ORDER);
                Settings.setLotNo(LOT_NO);
                Settings.setSTATUS(STATUS);
                Settings.setClsMax(CLS_MAX);
                Settings.setItemType(ITEM_TYPE);
                Settings.setMcType(ProductionSchedule.MACHINE.CLS.toString());
                Settings.setMACHINE(CLS_MC);
                Settings.setClsLot(CLS_LOT);

                // Discard the ScanManager class instance.
                mScanManager.removeDataListener(Search_ProcessSheet_Lot_Activity.this);
                // Discard the ScanManager class instance to release the resources.
                mScanManager.releaseScanManager();

                Intent intent = new Intent(Search_ProcessSheet_Lot_Activity.this, Classify_Output_Activity.class);
                startActivity(intent);
                finish();

            }else if (STATUS.trim().equals(ProductionSchedule.STATUS.CLASSIFY_FINISHED.toString())){
                new SweetAlertDialog(Search_ProcessSheet_Lot_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("สถานะ ProcessSheet : "+STATUS)
                        .show();

            }else {
                new SweetAlertDialog(Search_ProcessSheet_Lot_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("สถานะ ProcessSheet : "+STATUS)
                        .show();
            }
        } else{
            new SweetAlertDialog(Search_ProcessSheet_Lot_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("สถานะ ProcessSheet : "+STATUS)
                    .show();
        }
    }

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

            JSONObject json = new JSONObject();
            json.put("cmd", "check_status");
            json.put("sch_id",DICER_ID);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api")+ "/random_check.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){
                            Intent intent = new Intent(Search_ProcessSheet_Lot_Activity.this, Dicer_Activity.class);
                            startActivity(intent);
                            finish();
                        }else {
                            String id = jArray.getJSONObject(0).getString("id").trim();
                            String dicer_id = jArray.getJSONObject(0).getString("sch_id").trim();
                            String machine_code = jArray.getJSONObject(0).getString("machine_code").trim();
                            String random_type = jArray.getJSONObject(0).getString("random_type").trim();
                            String check_time = jArray.getJSONObject(0).getString("check_time").trim();

                            Intent intent = new Intent(Search_ProcessSheet_Lot_Activity.this, RandomCheck_Activity.class);
                            intent.putExtra("id",id);
                            intent.putExtra("sch_id",dicer_id);
                            intent.putExtra("machine_code",machine_code);
                            intent.putExtra("random_type",random_type);
                            intent.putExtra("check_time",check_time);
                            startActivity(intent);
                            finish();
                        }
                    }catch (JSONException e) {
                        layout_alert_save.setVisibility(View.GONE);
                        new SweetAlertDialog(Search_ProcessSheet_Lot_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_Lot_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Intent_OVEN() {
        // Discard the ScanManager class instance.
        mScanManager.removeDataListener(Search_ProcessSheet_Lot_Activity.this);
        // Discard the ScanManager class instance to release the resources.
        mScanManager.releaseScanManager();
        Intent intent = new Intent(Search_ProcessSheet_Lot_Activity.this, Oven_Activity.class);
        startActivity(intent);
        finish();

    }

    private void Clear_textview() {
        scan = 0;
        txt_ics.setText("");
        txt_job_order.setText("");
        txt_lot_no.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);
    }

}