package com.tomastc.bta500;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomastc.bta500.lib.KeyMapping;
import com.tomastc.bta500.lib.Scanner;
import com.tomastc.bta500.lib.Settings;
import com.tomastc.bta500.lib.WorkShopNo;
import com.tomastc.bta500.lib.common.AsyncHttpClient;
import com.tomastc.bta500.lib.common.MyAlert;
import com.tomastc.bta500.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.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class DirectLaborActivity extends Scanner implements View.OnClickListener {
    Spinner spinner_wks;
    Button btn_shift_A, btn_shift_B, btn_shift_other, btn_in, btn_out, btn_enter;
    TextView txt_user, txt_name, txt_wks_name,txt_process, txt_process_name, txt_message, txt_message_alert;
    String Shift, TranType, EMPLOYEE_ID, EMPLOYEE_NAME, str_date, str_date_time, str_time, WS_CD, MACHINE_LINE,SHIFT, WS_NO, User, str_msg;
    boolean b_confirm;
    ArrayList<String> item_wks;
    Map<String, WorkShopNo>map_wks;
    SimpleDateFormat date_fm, date_time_fm, time_fm;
    Calendar calendar;
    ConstraintLayout layout_alert;


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

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

        calendar = Calendar.getInstance();
        date_fm = new SimpleDateFormat("yyyyMMdd");
        date_time_fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        time_fm = new SimpleDateFormat("HHmmss");

        User =  Settings.getUserLogin_list().get(0).getUser_id();
        Log.d(getString(R.string.tag), "User: " + User);

        Shift = "";
        TranType = "";
        b_confirm = false;

        map_wks = new LinkedHashMap<>();
        item_wks = new ArrayList<String>();

        btn_shift_A = (Button) findViewById(R.id.btn_shift_A);
        btn_shift_B = (Button) findViewById(R.id.btn_shift_B);
        btn_shift_other = (Button) findViewById(R.id.btn_shift_other);
        btn_in = (Button) findViewById(R.id.btn_in);
        btn_out = (Button) findViewById(R.id.btn_out);
        btn_enter = (Button) findViewById(R.id.btn_enter);

        txt_user = (TextView) findViewById(R.id.txt_user);
        txt_name = (TextView) findViewById(R.id.txt_name);
        txt_wks_name = (TextView) findViewById(R.id.txt_wks_name);
        txt_process = (TextView) findViewById(R.id.txt_process);
        txt_process_name = (TextView) findViewById(R.id.txt_process_name);
        txt_message = (TextView) findViewById(R.id.txt_message);
        txt_message_alert = (TextView)findViewById(R.id.txt_message_alert);

        spinner_wks = (Spinner)findViewById(R.id.spinner_wks);

        Load_WorkShop();

    }

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

            case R.id.btn_shift_A:
                Shift = "A";
                btn_shift_A.setBackgroundResource(R.drawable.btn_select);
                btn_shift_B.setBackgroundResource(R.drawable.btn_shift_b);
                btn_shift_other.setBackgroundResource(R.drawable.btn_shift_other);

                break;

            case R.id.btn_shift_B:
                Shift = "B";
                btn_shift_B.setBackgroundResource(R.drawable.btn_select);
                btn_shift_A.setBackgroundResource(R.drawable.btn_shift_a);
                btn_shift_other.setBackgroundResource(R.drawable.btn_shift_other);

                break;
            case R.id.btn_shift_other:
                Shift = "O";
                btn_shift_other.setBackgroundResource(R.drawable.btn_select);
                btn_shift_A.setBackgroundResource(R.drawable.btn_shift_a);
                btn_shift_B.setBackgroundResource(R.drawable.btn_shift_b);

                break;
            case R.id.btn_in:
                TranType = "In";
                btn_in.setBackgroundResource(R.drawable.btn_select);
                btn_out.setBackgroundResource(R.drawable.btn_out);

                break;
            case R.id.btn_out:
                TranType = "Out";
                btn_out.setBackgroundResource(R.drawable.btn_select);
                btn_in.setBackgroundResource(R.drawable.btn_in);


                break;
            case R.id.btn_enter:
                if (b_confirm == false) {
                    Block_button();
                    Check_data();
                }
                break;
        }
    }

    private void Block_button() {
        b_confirm = true;
        btn_enter.setEnabled(false);
        btn_enter.setBackgroundResource(R.drawable.btn_select);
    }

    private void Unblock_button() {
        b_confirm = false;
        btn_enter.setEnabled(true);
        btn_enter.setBackgroundResource(R.drawable.button_backgroup_green);

    }


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

        try {
            txt_message.setText("");
            txt_message.setTextColor(Color.parseColor("#031064"));

            Log.d(getString(R.string.tag), "scan data : " + data);
            // Validate user code
            Check_Employee(data);

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

    private void Check_data() {
        if (txt_user.getText().toString().trim().equals("")){
            MyAlert alert =  new MyAlert(DirectLaborActivity.this);
            alert.setMessage("Please scan user id");
            alert.show();
            Unblock_button();

        }else if (Shift.trim().equals("")){
            MyAlert alert =  new MyAlert(DirectLaborActivity.this);
            alert.setMessage("Please select shift");
            alert.show();
            Unblock_button();

        }else if (TranType.trim().equals("")){
            MyAlert alert =  new MyAlert(DirectLaborActivity.this);
            alert.setMessage("Please select transaction type");
            alert.show();
            Unblock_button();

        }else {
            Check_TranType();

        }
    }

    private void Check_TranType() {
        layout_alert.setVisibility(View.VISIBLE);
        txt_message_alert.setText("Please wait, checking data...");
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        str_date = date_fm.format(calendar.getTime());
        str_msg = "";
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "check_tran_type");
            json.put("EMPLOYEE_ID", txt_user.getText().toString().trim());
            json.put("TRANS_DATE", str_date);
//            json.put("TRANS_TYPE", TranType);

            new AsyncHttpClient(getApplicationContext()
                    , Settings.getMgmtList().get("web_api") + "/nst_manpower_actual_plan.php"
                    , json.toString()
            ) {
                @Override
                public void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);
                    // update mapItems
                    try {
                        JSONArray jArray = new JSONArray(response);
                        Log.d(getString(R.string.tag), "response json length: " + jArray.length());

                        if (jArray.length() ==  0) {
                            if (TranType.trim().equals("Out")) {
                                str_msg = " ,this user not found tran : In";
                            }
                            Insert_data();
                        }else{
                            Insert_data();
                        }
//                        }else if (jArray.length() == 2){
//                            layout_alert.setVisibility(View.GONE);
//                                Unblock_button();
//                                MyAlert alert =  new MyAlert(DirectLaborActivity.this);
//                                alert.setMessage("Found data this user: In & Out ");
//                                alert.show();
//                        }else{
//                            JSONObject jsonObject = jArray.getJSONObject(0);
//                            String Q_tran_type = jsonObject.getString("TRANS_TYPE").trim();
//
//                            if (Q_tran_type.trim().equals("In")){
//                                if (TranType.trim().equals("In")){// in = in
//                                    layout_alert.setVisibility(View.GONE);
//                                    Unblock_button();
//                                    MyAlert alert =  new MyAlert(DirectLaborActivity.this);
//                                    alert.setMessage("Found data this user : In");
//                                    alert.show();
//                                }else {// in = out
//                                    Insert_data();
//                                }
//
//                            }else {//Out
//                                if (TranType.trim().equals("In")){// out = in
//                                    str_msg = ", found data this user : Out";
//
//                                }else {// out = out
//                                    layout_alert.setVisibility(View.GONE);
//                                    Unblock_button();
//                                    MyAlert alert =  new MyAlert(DirectLaborActivity.this);
//                                    alert.setMessage("Found data this user : Out");
//                                    alert.show();
//                                }
//
//                            }
//                        }

                    } catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        Log.e(getString(R.string.tag), e.getMessage());
                        MyAlert alert =  new MyAlert(DirectLaborActivity.this);
                        alert.setMessage("Incorrect scan information");
                        alert.show();
                    }
                }

                @Override
                protected void onError(Exception e) {
                    layout_alert.setVisibility(View.GONE);
                    MyAlert alert =  new MyAlert(DirectLaborActivity.this);
                    alert.setMessage(e.getMessage());
                    alert.show();
                }
            }.execute();
        } catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            Log.e(getString(R.string.tag), e.getMessage());
            MyAlert alert =  new MyAlert(DirectLaborActivity.this);
            alert.setMessage("Incorrect scan information");
            alert.show();
        }
    }

    private void Insert_data() {
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        str_date_time = date_time_fm.format(calendar.getTime());
        str_date = date_fm.format(calendar.getTime());
        str_time = time_fm.format(calendar.getTime());
        Log.d(getString(R.string.tag), "dt_to_server : " + str_date_time);
        Log.d(getString(R.string.tag), "date_server : " + str_date);
        Log.d(getString(R.string.tag), "time_server : " + str_time);

        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message_alert.setText("Please wait, saving data...");

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

            Map<String, String> jsonParams = new HashMap<>();
            jsonParams.put("EMPLOYEE_ID", txt_user.getText().toString().trim());
            jsonParams.put("TRANS_DATE", str_date);
            jsonParams.put("TRANS_TIME",str_time);
            jsonParams.put("WS_CD", WS_CD);
            jsonParams.put("MACHINE_LINE", txt_process.getText().toString().trim());
            jsonParams.put("SHIFT", Shift);
            jsonParams.put("TRANS_TYPE", TranType);
            jsonParams.put("PGM_NAME", "ACT_PLAN");
            jsonParams.put("ENTRY_DATE", str_date_time);
            jsonParams.put("CHG_USER_ID", User);
            JSONObject jsonObj = new JSONObject(jsonParams);
            jsonArray.put(jsonObj);

            json.put("manpower_datas",jsonArray);

            new AsyncHttpClient(getApplicationContext()
                    , Settings.getMgmtList().get("web_api") + "/nst_manpower_actual_plan.php"
                    , json.toString()
            ) {
                @Override
                public void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);
                    // update mapItems
                    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) {
                            txt_message.setText("Insert data complete"+str_msg);
                            layout_alert.setVisibility(View.GONE);
                            Clear_Layout();

                        } else {
                            layout_alert.setVisibility(View.GONE);
                            Unblock_button();
                            txt_message.setText("Can't insert data");
                            txt_message.setTextColor(Color.RED);
                        }
                    } catch (JSONException e) {
                        Unblock_button();
                        layout_alert.setVisibility(View.GONE);
                        txt_message.setText(e.getMessage());
                        txt_message.setTextColor(Color.RED);
                    }
                }
                @Override
                protected void onError(Exception e) {
                    Unblock_button();
                    layout_alert.setVisibility(View.GONE);
                    txt_message.setText(e.getMessage());
                    txt_message.setTextColor(Color.RED);
                }
            }.execute();
        } catch (Exception e) {
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            txt_message.setText(e.getMessage());
            txt_message.setTextColor(Color.RED);
        }
    }

    private void Clear_Layout() {
        txt_user.setText("");
        txt_name.setText("");
        txt_process.setText("");
        txt_process_name.setText("");
        spinner_wks.setSelection(0);
        Unblock_button();
    }


    private void Check_Employee(String data) {
        layout_alert.setVisibility(View.VISIBLE);
        txt_message_alert.setText("Please wait, searching data...");
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            json.put("EMPLOYEE_ID", data.trim());

            new AsyncHttpClient(getApplicationContext()
                    , Settings.getMgmtList().get("web_api") + "/nst_direct_employee_master.php"
                    , json.toString()
            ) {
                @Override
                public void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);
                    // update mapItems
                    try {
                        JSONArray jArray = new JSONArray(response);
                        Log.d(getString(R.string.tag), "response json length: " + jArray.length());

                        if (jArray.length() == 0) {
                            layout_alert.setVisibility(View.GONE);
                            MyAlert alert =  new MyAlert(DirectLaborActivity.this);
                            alert.setMessage("User not found!");
                            alert.show();
                            txt_user.setText("");
                            txt_name.setText("");

                        } else {
                            layout_alert.setVisibility(View.GONE);
                            JSONObject jsonObject = jArray.getJSONObject(0);
                            EMPLOYEE_ID = jsonObject.getString("EMPLOYEE_ID").trim();
                            EMPLOYEE_NAME =  jsonObject.getString("EMPLOYEE_NAME").trim();

                            txt_user.setText(EMPLOYEE_ID);
                            txt_name.setText(EMPLOYEE_NAME);

                            Check_ManPower_Plan(EMPLOYEE_ID);

                        }

                    } catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        Log.e(getString(R.string.tag), e.getMessage());
                        MyAlert alert =  new MyAlert(DirectLaborActivity.this);
                        alert.setMessage("Incorrect scan information");
                        alert.show();
                    }
                }

                @Override
                protected void onError(Exception e) {
                    layout_alert.setVisibility(View.GONE);
                    MyAlert alert =  new MyAlert(DirectLaborActivity.this);
                    alert.setMessage(e.getMessage());
                    alert.show();
                }
            }.execute();
        } catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            Log.e(getString(R.string.tag), e.getMessage());
            MyAlert alert =  new MyAlert(DirectLaborActivity.this);
            alert.setMessage("Incorrect scan information");
            alert.show();
        }
    }

    private void Check_ManPower_Plan(String employee_id) {
        layout_alert.setVisibility(View.VISIBLE);
        txt_message_alert.setText("Please wait, searching data...");
        WS_NO = "";
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        str_date = date_fm.format(calendar.getTime());
        Log.d(getString(R.string.tag), "dt_to_server : " + str_date);

        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            json.put("EMPLOYEE_ID", employee_id);
            json.put("BEG_EFF_DATE", str_date);


            new AsyncHttpClient(getApplicationContext()
                    , Settings.getMgmtList().get("web_api") + "/nst_manpower_alloc_plan.php"
                    , json.toString()
            ) {
                @Override
                public void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);
                    // update mapItems
                    try {
                        JSONArray jArray = new JSONArray(response);
                        Log.d(getString(R.string.tag), "response json length: " + jArray.length());

                        if (jArray.length() == 0) {
                            MyAlert alert =  new MyAlert(DirectLaborActivity.this);
                            alert.setMessage("Plan not found!");
                            alert.show();
                            layout_alert.setVisibility(View.GONE);

                        } else {
                            layout_alert.setVisibility(View.GONE);
                            JSONObject jsonObject = jArray.getJSONObject(0);
                            WS_CD = jsonObject.getString("WS_CD").trim();
                            MACHINE_LINE = jsonObject.getString("MACHINE_LINE").trim();
                            SHIFT = jsonObject.getString("SHIFT").trim();

                            WS_NO = WS_CD+MACHINE_LINE;

                            if (item_wks.contains(WS_NO)){
                                spinner_wks.setSelection(item_wks.indexOf(WS_NO));

                            }else {
                                MyAlert alert =  new MyAlert(DirectLaborActivity.this);
                                alert.setMessage("Not found WS_NO from lists");
                                alert.show();
                            }
                        }

                    } catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        Log.e(getString(R.string.tag), e.getMessage());
                        MyAlert alert =  new MyAlert(DirectLaborActivity.this);
                        alert.setMessage("Incorrect scan information");
                        alert.show();
                    }
                }

                @Override
                protected void onError(Exception e) {
                    layout_alert.setVisibility(View.GONE);
                    MyAlert alert =  new MyAlert(DirectLaborActivity.this);
                    alert.setMessage(e.getMessage());
                    alert.show();
                }
            }.execute();
        } catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            Log.e(getString(R.string.tag), e.getMessage());
            MyAlert alert =  new MyAlert(DirectLaborActivity.this);
            alert.setMessage("Incorrect scan information");
            alert.show();
        }
    }

    private void Load_WorkShop() {
        layout_alert.setVisibility(View.VISIBLE);
        txt_message_alert.setText("Please wait, loading data...");
        item_wks.clear();
        map_wks.clear();
        item_wks.add("");

        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            new AsyncHttpClient(getApplicationContext()
                    ,Settings.getMgmtList().get("web_api") + "/nst_ws_machine_master.php"
                    , json.toString()
            ) {
                @Override
                public void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);
                    // update mapItems
                    try {
                        JSONArray jArray = new JSONArray(response);
                        Log.d(getString(R.string.tag), "response json length: " + jArray.length());
                        if (jArray.length() == 0){
                            layout_alert.setVisibility(View.GONE);
                            MyAlert alert =  new MyAlert(DirectLaborActivity.this);
                            alert.setMessage("Not found data Wks.");
                            alert.show();

                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                item_wks.add(
                                        jArray.getJSONObject(i).getString("ws_no").trim()
                                );

                                map_wks.put(jArray.getJSONObject(i).getString("ws_no").trim(),
                                        new WorkShopNo(
                                                jArray.getJSONObject(i).getString("ws_cd").trim(),
                                                jArray.getJSONObject(i).getString("ws_no").trim(),
                                                jArray.getJSONObject(i).getString("mc_lineno").trim(),
                                                jArray.getJSONObject(i).getString("ws_desc").trim(),
                                                "", "",
                                                jArray.getJSONObject(i).getString("print_preset").trim(),
                                                jArray.getJSONObject(i).getString("INTERLOCK").trim()));
                            }
                            layout_alert.setVisibility(View.GONE);
                            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
                                    (getApplicationContext(), R.layout.spinner_usr_list, item_wks);
                            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            spinner_wks.setAdapter(dataAdapter);

                            spinner_wks.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                @Override
                                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                    String select = spinner_wks.getSelectedItem().toString().trim();
                                    if (map_wks.containsKey(select)) {
                                        WorkShopNo wks = map_wks.get(select);
                                        WS_CD = wks.getWs_cd();
                                        txt_process.setText(wks.getMc_line_no());
                                        txt_process_name.setText(wks.getWs_desc());

                                    } else {
                                        txt_process.setText("");
                                        txt_process_name.setText("");
                                    }
                                }

                                @Override
                                public void onNothingSelected(AdapterView<?> parent) {
                                    txt_process.setText("");
                                    txt_process_name.setText("");
                                }
                            });
                        }

                    } catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        MyAlert alert =  new MyAlert(DirectLaborActivity.this);
                        alert.setMessage(e.getMessage());
                        alert.show();
                    }
                }

                @Override
                protected void onError(Exception e) {
                    layout_alert.setVisibility(View.GONE);
                    MyAlert alert =  new MyAlert(DirectLaborActivity.this);
                    alert.setMessage(e.getMessage());
                    alert.show();
                }
            }
                    .execute();
        } catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            Log.e(getString(R.string.tag), e.getMessage());
            MyAlert alert =  new MyAlert(DirectLaborActivity.this);
            alert.setMessage(e.getMessage());
            alert.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:
                    finish();
                    break;

                case P2:
                    if (b_confirm == false) {
                        Block_button();
                        Check_data();
                    }
                    break;
            }
        }

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