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 android.widget.Toast;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.pcs_asi.Adapter.Lot_DB_Adapter;
import com.tomas.pcs_asi.ListData.Get_Lot_DB;
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.apache.http.conn.ConnectTimeoutException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeoutException;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class DB_Lot_Activity extends Scanner implements View.OnClickListener {
    TextView txt_header, txt_ics, txt_job_order, txt_qty_lot, txt_working, txt_wait_oven, txt_oven, txt_message;
    String str_process, str_ics, str_job, str_lot_no, str_qty_lot, str_working, str_finish, str_wait, str_oven,
    process_check, status_check, str_plan_start_dt, str_plan_end_dt, dt_format = "yyyy-MM-dd HH:mm:ss", str_sch_id, str_check_time,
    str_machine, str_user_id, str_qty_input;
    ConstraintLayout layout_alert;
    Calendar calendar;
    SimpleDateFormat date_time_fm;
    List<Get_Lot_DB> list_item;
    Lot_DB_Adapter lot_db_adapter;
    RecyclerView recyclerView;
    int scanned, diebond_process;
    boolean job_order;

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

        scanned = 0;
        job_order = false;
        date_time_fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        list_item = new ArrayList<Get_Lot_DB>();

        layout_alert = (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_working = (TextView) findViewById(R.id.txt_working);
        txt_wait_oven = (TextView) findViewById(R.id.txt_wait_oven);
        txt_oven = (TextView) findViewById(R.id.txt_oven);
        txt_message = (TextView)findViewById(R.id.txt_message);
        txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");

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

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

        if (!str_job.trim().equals("")){
            job_order = true;
            scanned = 1;
            Get_Schedule_Lot(str_ics, str_job);
        }

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

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imb_back:
                if (job_order == false ) {
                    Intent intent = new Intent(DB_Lot_Activity.this, DB_Schedule_Activity.class);
                    startActivity(intent);
                    finish();
                }else {
                    Intent intent = new Intent(DB_Lot_Activity.this, Search_ProcessSheet_Activity.class);
                    startActivity(intent);
                    finish();
                }
                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 (scanned == 0){
                str_job = data.trim();
                txt_job_order.setText("JOB ORDER : "+str_job);
                scanned = 1;
                Get_Schedule_Lot(str_ics, str_job);

            }else {
                scanned = 0;
                str_lot_no = data.trim();
                Log.d(getString(R.string.tag), "lot_no : " + str_lot_no);
                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 Get_Schedule_Lot(String str_ics, String job_order) {
        list_item.clear();
        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");

            JSONObject json = new JSONObject();
            json.put("cmd", "get_sch_lot_db");
            json.put("ics_product", str_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);
                        if (jArray.length() == 0){
                            View_data();
                            layout_alert.setVisibility(View.GONE);
                            txt_job_order.setText("JOB ORDER : ");
                            txt_qty_lot.setText("LOT");
                            txt_working.setText("");
                            txt_wait_oven.setText("");
                            txt_oven.setText("");
                            str_job = "";
                            scanned = 0;
                            Toast.makeText(getApplicationContext(), "ไม่พบ Production Plan!", Toast.LENGTH_LONG).show();

                        }else {
                            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_wait = jArray.getJSONObject(i).getString("WAIT_OVEN").trim();
                                str_oven = jArray.getJSONObject(i).getString("OVEN").trim();
                                list_item.add(new Get_Lot_DB(
                                        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(),
                                        jArray.getJSONObject(i).getString("oven_diebond_act_end_dt").trim() == "null" ? "" : jArray.getJSONObject(i).getString("oven_diebond_act_end_dt").trim(),
                                        str_finish,
                                        str_working,
                                        str_wait,
                                        str_oven));
                            }
                            layout_alert.setVisibility(View.GONE);
                            txt_working.setText(str_working);
                            txt_wait_oven.setText(str_wait);
                            txt_oven.setText(str_oven);
                            txt_qty_lot.setText(str_finish + " / "+str_qty_lot+ " LOT");
                            View_data();
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(DB_Lot_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(DB_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_db_adapter = new Lot_DB_Adapter(list_item, DB_Lot_Activity.this, "DIE_BOND");
        recyclerView.setAdapter(lot_db_adapter);
        Log.d(getString(R.string.tag), "set adapter");
    }

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

            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){
                            scanned = 1;
                            str_lot_no = "";
                            layout_alert.setVisibility(View.GONE);
                            Toast.makeText(getApplicationContext(), "ไม่พบ Lot no.!", Toast.LENGTH_LONG).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("qty_in_lot").trim();
                                str_qty_input = jArray.getJSONObject(i).getString("diebond_output").trim() == "null" ? jArray.getJSONObject(i).getString("qty_in_lot").trim() : jArray.getJSONObject(i).getString("diebond_output").trim();
                                str_machine = jArray.getJSONObject(i).getString("diebond_machine").trim() == "null" ? "" : jArray.getJSONObject(i).getString("diebond_machine").trim();
                                str_user_id = jArray.getJSONObject(i).getString("diebond_start_user_id").trim() == "null" ? "" : jArray.getJSONObject(i).getString("diebond_start_user_id").trim();

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

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

                            Check_Status();

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

    private void Check_Status() {
        if (status_check.trim().equals(ProductionSchedule.STATUS.IMPORTED.toString())) {
            //first check
            str_check_time = "1";
            Check_Plan_start_end(str_plan_start_dt, "Start Plan DIE BOND");

        }else if (status_check.trim().equals(ProductionSchedule.STATUS.DIE_BOND_AGAIN.toString())){
                Check_Diebond_Times();

        }else if (status_check.trim().equals(ProductionSchedule.STATUS.DIE_BOND_WORKING.toString())){
                Check_Diebond_Times();
//                Check_Plan_start_end(str_plan_end_dt, "Finish Plan DIE BOND");

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

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

            JSONObject json = new JSONObject();
            json.put("cmd", "check_times");
            json.put("sch_id", str_sch_id);
            json.put("process", str_process);

            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 {
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() == 0){
                            str_check_time = "1";

                        }else {
                            int times = 0;
                            for (int i = 0; i < jArray.length(); i++){
                                times = jArray.getJSONObject(i).getInt("times");
                            }

                            Log.d(getString(R.string.tag), "check DB: " + times+":"+diebond_process );
                            if (status_check.trim().equals(ProductionSchedule.STATUS.DIE_BOND_AGAIN.toString())){
                                times = (times + 1);
                                str_check_time = String.valueOf(times);
                                Check_Plan_start_end("","");

                            }else {//DIE_BOND_WORKING
                                str_check_time = String.valueOf(times);
                                if (times == diebond_process) {//diebond ครบตามที่กำหนด
                                    Check_Plan_start_end(str_plan_end_dt, "Finish Plan DIE BOND");
                                }else {
                                    Check_Plan_start_end("","");
                                }
                            }
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(DB_Lot_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(DB_Lot_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Check_Plan_start_end(String plan_dt, String message) {
        if (!plan_dt.trim().equals("") && !message.trim().equals("")) {
            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("");
            }
        }else {
            Settings.setOverdueDt("");
            Settings.setOverdueTitle("");
        }

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

        Settings.setJobOrder(str_job);
        Settings.setLotNo(str_lot_no);
        Settings.setSTATUS(status_check);
        Settings.setMcType(ProductionSchedule.MACHINE.DB.toString());
        Settings.setSchId(str_sch_id);
        Settings.setUserId(str_user_id);
        Settings.setMACHINE(str_machine);
        Settings.setQtyInput(str_qty_input);
        Settings.setCheckTime(str_check_time);

        Check_Random_Status();
    }

    private void Check_Random_Status() {
        try {
            layout_alert.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){
                            Intent intent = new Intent(DB_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(DB_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.setVisibility(View.GONE);
                        new SweetAlertDialog(DB_Lot_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(DB_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:
                    if (job_order == false ) {
                        Intent intent = new Intent(DB_Lot_Activity.this, DB_Schedule_Activity.class);
                        startActivity(intent);
                        finish();
                    }else {
                        Intent intent = new Intent(DB_Lot_Activity.this, Search_ProcessSheet_Activity.class);
                        startActivity(intent);
                        finish();
                    }
                    break;

            }
        }

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