package com.tomas.pcs_asi;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

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.Adapter.Lot_Plasma_Adapter;
import com.tomas.pcs_asi.ListData.Get_Lot_Plasma;
import com.tomas.pcs_asi.lib.ConvertStringToCalendar;
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.ArrayList;
import java.util.Calendar;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class Plasma_Lot_Activity extends Scanner implements View.OnClickListener {
    TextView txt_header, txt_ics, txt_job_order, txt_qty_lot, txt_plasma, txt_plasma_finish, txt_working, txt_message;
    RecyclerView view_sch_lot;
    String str_ics, str_job, str_process, str_finish, str_working, str_plasma, str_plasma_finished, str_qty_lot, str_lot_no,
            process_check, status_check, str_sch_id, str_qty_input, str_machine_plasma, str_machine_wb, str_user_plasma, str_user_wb, str_mag_no, plasma_plan_start_dt, plasma_plan_end_dt,
            wb_plan_start_dt, wb_plan_end_dt, dt_format = "yyyy-MM-dd HH:mm:ss", plasma_act_start_dt, plasma_mag_no;
//            wirebond_equipment, wirebond_equipment_exp;
    List<Get_Lot_Plasma> list_item;
    Calendar calendar;
    SimpleDateFormat date_time_fm;
    Lot_Plasma_Adapter lot_plasma_adapter;
    ConstraintLayout layout_alert_save;

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

        list_item = new ArrayList<Get_Lot_Plasma>();
        date_time_fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

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

        txt_header = (TextView) findViewById(R.id.txt_header_lot);
        txt_ics = (TextView) findViewById(R.id.txt_ics);
        txt_job_order = (TextView) findViewById(R.id.txt_job_order);
        txt_qty_lot = (TextView) findViewById(R.id.txt_qty_lot);
        txt_plasma = (TextView) findViewById(R.id.txt_plasma);
        txt_plasma_finish = (TextView) findViewById(R.id.txt_plasma_end);
        txt_working = (TextView) findViewById(R.id.txt_working);
        txt_message = (TextView)findViewById(R.id.txt_message);

        view_sch_lot = (RecyclerView)findViewById(R.id.view_sch_lot);
        view_sch_lot.setHasFixedSize(true);
        view_sch_lot.setRecycledViewPool(new RecyclerView.RecycledViewPool());
        view_sch_lot.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        view_sch_lot.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        view_sch_lot.setItemAnimator(new DefaultItemAnimator());

        str_process = Settings.getPROCESS();
        str_ics = Settings.getICS();
        str_job = Settings.getJobOrder();

        txt_header.setText(str_process+" LOT");
        txt_ics.setText("ICS : "+str_ics);
        txt_job_order.setText("JOB ORDER : "+str_job);

        Get_Schedule_Lot(str_ics, str_job);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imb_back:
                Intent intent = new Intent(Plasma_Lot_Activity.this, Search_ProcessSheet_Activity.class);
                startActivity(intent);
                finish();
                break;
        }
    }

    private void Get_Schedule_Lot(String ics, String job_order) {
        list_item.clear();
        layout_alert_save.setVisibility(View.VISIBLE);
        txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "get_sch_lot_plasma");
            json.put("ics_product", ics);
            json.put("job_order", job_order);

            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);
                            for (int i = 0; i < jArray.length(); i++){

                                str_qty_lot = jArray.getJSONObject(i).getString("Qty_Lot").trim();
                                str_finish =   jArray.getJSONObject(i).getString("FINISHED").trim();
                                str_working = jArray.getJSONObject(i).getString("WORKING").trim();
                                str_plasma = jArray.getJSONObject(i).getString("PLASMA").trim();
                                str_plasma_finished = jArray.getJSONObject(i).getString("PLASMA_FINISHED").trim();

                                list_item.add(new Get_Lot_Plasma(
                                        jArray.getJSONObject(i).getString("sch_id").trim(),
                                        jArray.getJSONObject(i).getString("ICSProductCode").trim(),
                                        str_qty_lot,
                                        jArray.getJSONObject(i).getString("lot_no").trim(),
                                        jArray.getJSONObject(i).getString("process").trim(),
                                        jArray.getJSONObject(i).getString("status").trim(),
                                        str_finish,
                                        str_working,
                                        str_plasma,
                                        str_plasma_finished,
                                        jArray.getJSONObject(i).getString("wirebond_act_end_dt").trim() == "null" ? "" : jArray.getJSONObject(i).getString("wirebond_act_end_dt").trim()));
                            }
                            txt_working.setText(str_working);
                            txt_plasma.setText(str_plasma);
                            txt_plasma_finish.setText(str_plasma_finished);
                            txt_qty_lot.setText(str_finish + " / "+str_qty_lot+ " LOT");
                            View_data();
                        layout_alert_save.setVisibility(View.GONE);
                    }catch (JSONException e) {
                        layout_alert_save.setVisibility(View.GONE);
                        new SweetAlertDialog(Plasma_Lot_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void View_data() {
        Log.d(getString(R.string.tag), String.valueOf(list_item.size()));

        lot_plasma_adapter = new Lot_Plasma_Adapter(list_item, Plasma_Lot_Activity.this);
        view_sch_lot.setAdapter(lot_plasma_adapter);
        Log.d(getString(R.string.tag), "set adapter");
    }

    @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 (!data.trim().equals("")){
                str_lot_no = data.trim();
                Check_ProcessSheet(str_ics, str_job, str_lot_no);

            }
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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

    private void Check_ProcessSheet(String ics, String job_order, String lot_no) {
        layout_alert_save.setVisibility(View.VISIBLE);
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "check_process_sheet");
            json.put("ics_product", ics);
            json.put("job_order", job_order);
            json.put("lot_no", lot_no);

            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){
                            layout_alert_save.setVisibility(View.GONE);
                            str_lot_no = "";
                            new SweetAlertDialog(Plasma_Lot_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ Lot no.!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++){
                                process_check = jArray.getJSONObject(i).getString("process").trim();
                                status_check = jArray.getJSONObject(i).getString("status").trim();
                                str_sch_id = jArray.getJSONObject(i).getString("sch_id").trim();
                                str_qty_input = jArray.getJSONObject(i).getString("diebond_output").trim()== "null" ? "" : jArray.getJSONObject(i).getString("diebond_output").trim();
                                str_machine_plasma = jArray.getJSONObject(i).getString("plasma_machine").trim() == "null" ? "" : jArray.getJSONObject(i).getString("plasma_machine").trim();
                                str_user_plasma = jArray.getJSONObject(i).getString("plasma_start_user_id").trim() == "null" ? "" : jArray.getJSONObject(i).getString("plasma_start_user_id").trim();
                                str_mag_no = jArray.getJSONObject(i).getString("oven_diebond_mag_no").trim() == "null" ? "" : jArray.getJSONObject(i).getString("oven_diebond_mag_no").trim();
                                plasma_mag_no = jArray.getJSONObject(i).getString("plasma_mag_no").trim() == "null" ? "" : jArray.getJSONObject(i).getString("plasma_mag_no").trim();
                                str_machine_wb = jArray.getJSONObject(i).getString("wirebond_machine").trim() == "null" ? "" : jArray.getJSONObject(i).getString("wirebond_machine").trim();
                                str_user_wb = jArray.getJSONObject(i).getString("wirebond_start_user_id").trim() == "null" ? "" : jArray.getJSONObject(i).getString("wirebond_start_user_id").trim();
//                                wirebond_equipment= jArray.getJSONObject(i).getString("wirebond_equipment").trim() == "null" ? "" : jArray.getJSONObject(i).getString("wirebond_equipment").trim();
//                                wirebond_equipment_exp= jArray.getJSONObject(i).getString("wirebond_equipment_exp").trim() == "null" ? "" : jArray.getJSONObject(i).getString("wirebond_equipment_exp").trim();

                                JSONObject obj = jArray.getJSONObject(i);
                                JSONObject array_start_dt = obj.getJSONObject("plasma_plan_start_dt");
                                plasma_plan_start_dt = array_start_dt.getString("date");
                                plasma_plan_start_dt = plasma_plan_start_dt.substring(0,19);
                                Log.d(getString(R.string.tag), "plasma_plan_start_dt: " + plasma_plan_start_dt);

                                JSONObject array_end_dt = obj.getJSONObject("plasma_plan_end_dt");
                                plasma_plan_end_dt = array_end_dt.getString("date");
                                plasma_plan_end_dt = plasma_plan_end_dt.substring(0,19);
                                Log.d(getString(R.string.tag), "plasma_plan_end_dt: " + plasma_plan_end_dt);

                                JSONObject array_wb_start_dt = obj.getJSONObject("wirebond_plan_start_dt");
                                wb_plan_start_dt = array_wb_start_dt.getString("date");
                                wb_plan_start_dt = wb_plan_start_dt.substring(0,19);
                                Log.d(getString(R.string.tag), "wb_plan_start_dt: " + wb_plan_start_dt);
//
                                JSONObject array_wb_end_dt = obj.getJSONObject("wirebond_plan_end_dt");
                                wb_plan_end_dt = array_wb_end_dt.getString("date");
                                wb_plan_end_dt = wb_plan_end_dt.substring(0,19);
                                Log.d(getString(R.string.tag), "wb_plan_end_dt: " + wb_plan_end_dt);

                                String act_start = jArray.getJSONObject(i).getString("plasma_act_start_dt");
                                if (act_start.trim().equals("")||act_start.trim().equals("null")){
                                    plasma_act_start_dt = "";
                                }else{
                                    JSONObject plasma_act_start = obj.getJSONObject("plasma_act_start_dt");
                                    plasma_act_start_dt = plasma_act_start.getString("date");
                                    plasma_act_start_dt = plasma_act_start_dt.substring(0,19);
                                    Log.d(getString(R.string.tag), "plasma_act_start_dt: " + plasma_act_start_dt);
                                }
//                                if (jArray.getJSONObject(i).getString("wirebond_equipment_exp").trim() == "null"){
//                                    wirebond_equipment_exp = "";
//                                }else {
//                                    JSONObject array_eqm_exp = obj.getJSONObject("wirebond_equipment_exp");
//                                    wirebond_equipment_exp = array_eqm_exp.getString("date");
//                                    wirebond_equipment_exp = wirebond_equipment_exp.substring(0, 10);
//                                }

                            }
                            Check_Status();

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

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

    private void Check_Status() {
        if (status_check.trim().equals(ProductionSchedule.STATUS.DIE_BOND_FINISHED.toString())) {
            Check_Plan_start_end(plasma_plan_start_dt, "Start Plan PLASMA", "PLASMA" );

        } else if (status_check.trim().equals(ProductionSchedule.STATUS.PLASMA.toString())){//WIRE_BOND
               //status plasma, plasma_finished, working, finished
                Settings.setMACHINE(str_machine_plasma);
                Settings.setStartDt(plasma_act_start_dt);
                Check_Plan_start_end(plasma_plan_end_dt, "Finish Plan PLASMA", "PLASMA");

        }else if (status_check.trim().equals(ProductionSchedule.STATUS.PLASMA_FINISHED.toString())){
                Settings.setMcType(ProductionSchedule.MACHINE.WB.toString());
                Check_Plan_start_end(wb_plan_start_dt, "Start Plan WIRE BOND", "WIRE_BOND");

        }else if (status_check.trim().equals(ProductionSchedule.STATUS.WIRE_BOND_WORKING.toString())){
                Settings.setMcType(ProductionSchedule.MACHINE.WB.toString());
                Settings.setMACHINE(str_machine_wb);
                Settings.setUserId(str_user_wb);
                Settings.setQtyInput(str_qty_input);
//                Settings.setEQM(wirebond_equipment);
//                Settings.setEqmExp(wirebond_equipment_exp);
                Check_Plan_start_end(wb_plan_end_dt, "Finish Plan WIRE BOND", "WIRE_BOND");

        }else if (status_check.trim().equals(ProductionSchedule.STATUS.WIRE_BOND_FINISHED.toString())){
            layout_alert_save.setVisibility(View.GONE);
                new SweetAlertDialog(Plasma_Lot_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("สถานะ Process sheet \n WIRE_BOND_FINISHED")
                        .show();
        }else{
            layout_alert_save.setVisibility(View.GONE);
                new SweetAlertDialog(Plasma_Lot_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("สถานะ Process sheet \n "+process_check+" : "+status_check)
                        .show();
        }
    }

    private void Check_Plan_start_end(String plan_dt, String message, String plasma) {
        calendar = ConvertStringToCalendar.convert(plan_dt,dt_format);
        String p_date1 = date_time_fm.format(calendar.getTime());
        Log.d(getString(R.string.tag), "calendar: " + p_date1);

        calendar.add(Calendar.MINUTE, 30);
        String p_date2 = date_time_fm.format(calendar.getTime());
        Log.d(getString(R.string.tag), "calendar: " + p_date2);

        Calendar now = Calendar.getInstance();
        Calendar now_dt = (Calendar) now.clone();
        String str_now = date_time_fm.format(now_dt.getTime());
        Log.d(getString(R.string.tag), "now_dt: " + str_now);

        if (now_dt.after(calendar)){
            Log.d(getString(R.string.tag), "if alert");
            Settings.setOverdueDt(plan_dt);
            Settings.setOverdueTitle(message);
        }else {
            Log.d(getString(R.string.tag), "else ");
            Settings.setOverdueDt("");
            Settings.setOverdueTitle("");
        }

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

        Settings.setSchId(str_sch_id);
        Settings.setLotNo(str_lot_no);
        Settings.setSTATUS(status_check);

        Check_Random_Status(plasma);


    }

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

            JSONObject json = new JSONObject();
            json.put("cmd", "check_status");
            json.put("sch_id", str_sch_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){
                            if(plasma.trim().equals("PLASMA")){
                                Settings.setMagNo(str_mag_no);
                                Intent intent = new Intent(Plasma_Lot_Activity.this, Plasma_Activity.class);
                                startActivity(intent);
                                finish();
                            }else{
                                Settings.setMagNo(plasma_mag_no);
                                Intent intent = new Intent(Plasma_Lot_Activity.this, Process_Activity.class);
                                startActivity(intent);
                                finish();
                            }
                        }else {
                            String id = jArray.getJSONObject(0).getString("id").trim();
                            String sch_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(Plasma_Lot_Activity.this, RandomCheck_Activity.class);
                            intent.putExtra("id",id);
                            intent.putExtra("sch_id",sch_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(Plasma_Lot_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert_save.setVisibility(View.GONE);
            new SweetAlertDialog(Plasma_Lot_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(Plasma_Lot_Activity.this, Search_ProcessSheet_Activity.class);
                    startActivity(intent);
                    finish();
                    break;
            }
        }

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