package com.tomas.ht_ydt;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.ht_ydt.Adapter.StocktakingLabel_Adapter;
import com.tomas.ht_ydt.ListData.LabelItem_list;
import com.tomas.ht_ydt.lib.KeyMapping;
import com.tomas.ht_ydt.lib.Scanner;
import com.tomas.ht_ydt.lib.Settings;
import com.tomas.ht_ydt.lib.common.AsyncHttpClient;
import com.tomas.ht_ydt.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.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class Stocktaking_Activity extends Scanner implements View.OnClickListener {

    TextView txt_user, txt_device, txt_location;
    ImageButton imb_back;
    Button btn_clear, btn_confirm;
    RecyclerView view_data;
    String str_location;
    Map<String, LabelItem_list> map_label;
    Calendar calendar;
    boolean b_confirm;
    List<LabelItem_list> list_label;
    StocktakingLabel_Adapter label_adapter;

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

        b_confirm = false;
        map_label = new LinkedHashMap<>();
        list_label = new ArrayList<LabelItem_list>();
        calendar = Calendar.getInstance();

        txt_user = (TextView) findViewById(R.id.txt_user);
        txt_user.setText("User : "+ Settings.getLoginUser().getName());
        txt_device = (TextView) findViewById(R.id.txt_device);
        txt_device.setText("Device : "+Settings.getDeviceNo());

        txt_location = (TextView) findViewById(R.id.txt_location);

        btn_clear = (Button)findViewById(R.id.btn_clear);
        btn_confirm = (Button)findViewById(R.id.btn_confirm);
        imb_back = (ImageButton)findViewById(R.id.imb_back);

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

    }

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

            case R.id.btn_clear:
                Clear_layout();
                break;

            case R.id.btn_confirm:
                if (b_confirm == false) {
                    Block_button();
                    UpdateStocktaking();
                }
                break;
        }
    }
    private void Clear_layout() {
        Unblock_button();
        map_label.clear();
        txt_location.setText("");
        str_location = "";
        View_data();
    }

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

    private void Unblock_button() {
        b_confirm = false;
        btn_confirm.setEnabled(true);
        btn_confirm.setBackgroundResource(R.drawable.button_background_blue);
    }


    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
        if (data.trim().equals("") || b_confirm == true)
            return;
        try {
            Log.d(getString(R.string.tag), "data read:" + data);

            String[] tokens = data.split(getString(R.string.DELIMITER_SCAN_TOKEN),-1);
            Log.d(getString(R.string.tag), Arrays.deepToString(tokens));

            if (tokens.length == 4){
                if (txt_location.getText().toString().trim().equals("")){
                    showWarning("Please scan location!!");

                }else {
                    Label_Inquiry(tokens[0].trim(), tokens[1].trim(), tokens[2].trim(), tokens[3].trim());
                }
            }else if (tokens.length == 2){//scan location
                if (txt_location.getText().toString().trim().equals("")||map_label.size() == 0) {
                    str_location = tokens[0].trim();
                    if (Settings.getMap_location().containsKey(str_location)){
                        txt_location.setText(str_location);

                    }else {
                        showWarning("Location not found!!");
                    }
                }else {
                    showWarning("Can't change location!!");
                }
            }else {
                showWarning("Invalid QR code!!");
            }

            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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

    private void Label_Inquiry(String parts_no, String lot_no, String serial_no, String label_id) {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "LABEL/DETAIL");
            json.put("parts_no", parts_no);
            json.put("lot_no", lot_no);
            json.put("serial_no", serial_no);
            json.put("id", label_id);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/ht_api.php",
                    json.toString()) {
                @SuppressLint("StaticFieldLeak")
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);

                    try{
                        JSONObject jsonObject = new JSONObject(response);
                        String value = jsonObject.getString("value");
                        JSONArray jArray = new JSONArray(value);
                        if (jArray.length() == 0){
                            showWarning("Label not found!");

                        }else {
                            String status_label = jArray.getJSONObject(0).getString("status").trim();
                            String last_location = jArray.getJSONObject(0).getString("last_location_id").trim();
                            String id_label = jArray.getJSONObject(0).getString("id").trim();
                            Log.d(getString(R.string.tag), "response: " + id_label+" / "+last_location+" / "+status_label);
                            //check duplicate label in map
                            if (map_label.containsKey(id_label)) {
                                new SweetAlertDialog(Stocktaking_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("WARNING")
                                        .setContentText("This Label has been scanned.")
                                        .setCancelText(" Delete")
                                        .showCancelButton(true)
                                        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                            @Override
                                            public void onClick(SweetAlertDialog sDialog) {
                                                sDialog.dismiss();
                                                map_label.remove(id_label);
                                                Log.d(getString(R.string.tag), "map_label size = " + map_label.size());
                                                View_data();
                                            }
                                        })
                                        .setConfirmText("Continue")
                                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                            @Override
                                            public void onClick(SweetAlertDialog sDialog) {
                                                sDialog.dismiss();
                                            }
                                        })
                                        .show();
                            } else {
                                map_label.put(jArray.getJSONObject(0).getString("id").trim(), new LabelItem_list(
                                        "",
                                        jArray.getJSONObject(0).getString("id").trim(),
                                        jArray.getJSONObject(0).getString("lot_no").trim(),
                                        jArray.getJSONObject(0).getString("serial_no").trim(),
                                        jArray.getJSONObject(0).getString("status").trim(),
                                        String.valueOf(Math.round(Double.parseDouble(jArray.getJSONObject(0).getString("issue_qty").trim()))),
                                        jArray.getJSONObject(0).getString("issue_stock_qty").trim(),
                                        jArray.getJSONObject(0).getString("act_stock_qty").trim(),
                                        jArray.getJSONObject(0).getString("control_unit").trim(),
                                        jArray.getJSONObject(0).getString("lbl_supplier_id").trim(),
                                        jArray.getJSONObject(0).getString("lbl_supplier").trim(),
                                        jArray.getJSONObject(0).getString("lbl_part_no").trim(),
                                        jArray.getJSONObject(0).getString("lbl_part_name").trim(),
                                        jArray.getJSONObject(0).getString("lbl_unit").trim(),
                                        jArray.getJSONObject(0).getString("lbl_ng").trim(),
                                        jArray.getJSONObject(0).getString("last_location_id").trim().equals("null") ? "" : jArray.getJSONObject(0).getString("last_location_id").trim(),
                                        jArray.getJSONObject(0).getString("last_location_name").trim().equals("null") ? "" : jArray.getJSONObject(0).getString("last_location_name").trim(),
                                        "",
                                        "",
                                        jArray.getJSONObject(0).getString("lbl_order_no").trim()));

                                View_data();
                            }
                        }
                    }catch (JSONException e) {
                        new SweetAlertDialog(Stocktaking_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            new SweetAlertDialog(Stocktaking_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void View_data() {
        list_label.clear();
        int no = 0;
        Log.d(getString(R.string.tag),"mapItem"+ String.valueOf(map_label.size()));
        for (String key : map_label.keySet()){
            no = (no + 1);
            LabelItem_list item = map_label.get(key);
            list_label.add(new LabelItem_list(
                    String.valueOf(no),
                    item.getLabel_id(),
                    item.getLot_no(),
                    item.getSerial_no(),
                    item.getStatus(),
                    item.getIssue_qty(),
                    item.getIssue_stock_qty(),
                    item.getAct_stock_qty(),
                    item.getControl_unit(),
                    item.getLbl_supplier_id(),
                    item.getLbl_supplier(),
                    item.getLbl_part_no(),
                    item.getLbl_part_name(),
                    item.getLbl_unit(),
                    item.getLbl_ng(),
                    item.getLast_location_id(),
                    item.getLast_location_name(),
                    item.getLocation(),
                    item.getLocation_name(),
                    item.getLbl_order_no()));//location

            Log.d(getString(R.string.tag),"getLabel_id"+ String.valueOf(item.getLabel_id()));
        }
        label_adapter = new StocktakingLabel_Adapter(list_label, this);
        view_data.setAdapter(label_adapter);
        Log.d(getString(R.string.tag), "set adapter");

        if (map_label.size() == 0){
            btn_confirm.setEnabled(false);
            btn_confirm.setBackgroundResource(R.drawable.button_background_gray);
        }else {
            if (b_confirm == true){
                btn_confirm.setEnabled(false);
                btn_confirm.setBackgroundResource(R.drawable.button_background_gray);
            }else {
                btn_confirm.setEnabled(true);
                btn_confirm.setBackgroundResource(R.drawable.button_background_blue);
            }
        }
    }

    private void UpdateStocktaking() {
        if (map_label.size() == 0)
            return;

        Block_button();
        calendar = Calendar.getInstance();
        SimpleDateFormat date_time = new SimpleDateFormat("yyyyMM");
        String str_date = date_time.format(calendar.getTime());
        Log.d(getString(R.string.tag), "str_date: " + str_date);

        Log.d(getString(R.string.tag), "UpdateStocktaking");
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "STOCKTAKING/ADD");

            JSONArray jsonArray = new JSONArray();
            for (String key : map_label.keySet()) {
                LabelItem_list item = map_label.get(key);
                Map<String, String> jsonParams = new HashMap<>();
                jsonParams.put("label_id", item.getLabel_id());
                jsonParams.put("serial_no", item.getSerial_no());
                jsonParams.put("item_id", item.getLbl_part_no());
                jsonParams.put("location_id", txt_location.getText().toString().trim());
                jsonParams.put("lot_no", item.getLot_no());
                jsonParams.put("taking_month", str_date);
                jsonParams.put("st_qty", item.getIssue_stock_qty());
                jsonParams.put("qty", item.getIssue_stock_qty());
                jsonParams.put("control_unit", item.getControl_unit());
                jsonParams.put("create_user_id", Settings.getLoginUser().getId());

                JSONObject jsonObject = new JSONObject(jsonParams);
                jsonArray.put(jsonObject);
                json.put("stock_datas", jsonArray);
            }

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/ht_api.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 || response.trim().equals("")){
                            Unblock_button();
                            showError("Can't register stocktaking data!!");
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                try {
                                    String id_label = jArray.getJSONObject(i).getString("label_id");
                                    String status = jArray.getJSONObject(i).getString("status");
                                    int affected_rows = jArray.getJSONObject(i).getInt("affected_rows");

                                    Log.d(getString(R.string.tag), "jArray: " + id_label + "|" + status + "|" + affected_rows);

                                    LabelItem_list item = map_label.get(id_label);
                                    if (status.trim().equals("success") && affected_rows == 1) {
                                        item.setStatus("OK");
                                    } else {
                                        item.setStatus("NG");
                                    }
                                    map_label.put(id_label, item);

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            View_data();
                            showSuccess("Insert stocktaking completed!!");
                        }
                    }catch (JSONException e) {
                        Unblock_button();
                        e.printStackTrace();
                    }
                }
            }.execute();

        } catch (Exception e) {
            Unblock_button();
            Log.e(getString(R.string.tag), e.getMessage());
        }
    }

    @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:
                    imb_back.performClick();
                    break;

                case P3:
                    btn_clear.performClick();
                    break;

                case P4://confirm
                    btn_confirm.performClick();
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }

}