package com.tomastc.ht_nki;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

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.tomastc.ht_nki.Adapter.Tranfer_Adapter;
import com.tomastc.ht_nki.ListData.Tranfer_list;
import com.tomastc.ht_nki.lib.KeyMapping;
import com.tomastc.ht_nki.lib.Scanner;
import com.tomastc.ht_nki.lib.Settings;
import com.tomastc.ht_nki.lib.common.AsyncHttpClient;
import com.tomastc.ht_nki.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.List;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class TireTransfer_Activity extends Scanner implements View.OnClickListener,ClickRowQCScheculeDetail {


    TextView txt_ticket_no, txt_user, txt_device, txt_location,txt_qty_total;
    Button btn_clear, btn_confirm;
    RecyclerView view_data;
    String str_location;
    Map<String, Tranfer_list> map_label;
    Calendar calendar;
    boolean b_confirm;
    List<Tranfer_list> list_label;
    Tranfer_Adapter label_adapter;

    Button btn_ok,btn_cancel;

    EditText edt_qty;
    String  str_id;

    Dialog dialog;

    RelativeLayout popupLayout4;

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

        b_confirm = false;
        map_label = new LinkedHashMap<>();
        list_label = new ArrayList<Tranfer_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_ticket_no = (TextView) findViewById(R.id.txt_ticket_no);

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

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


        popupLayout4 = (RelativeLayout) findViewById(R.id.popupLayout4);
        popupLayout4.setVisibility(GONE);
        btn_ok = (Button) findViewById(R.id.btn_ok);
        btn_cancel = (Button) findViewById(R.id.btn_cancel);
        txt_qty_total = (TextView)findViewById(R.id.txt_qty_total);


        edt_qty = (EditText) findViewById(R.id.txt_real_qty);
        edt_qty.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
                if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                        (keyCode == KeyEvent.KEYCODE_ENTER)) {

                    btn_ok.performClick();


                    return true;
                }
                return false;
            }
        });
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(edt_qty.getText().toString().length()>0) {
                    popupLayout4.setVisibility(GONE);


                    for (int i = 0; i < list_label.size(); i++) {


                        Integer item_qty = Integer.parseInt(list_label.get(i).getQty().toString());
                        String id = list_label.get(i).getPart_no() + list_label.get(i).getBc_tire();


                        if (id.equals(str_id)) {


                            Integer edit_qty = Integer.parseInt(edt_qty.getText().toString());
                            if (edit_qty > item_qty && item_qty > 0) {

                                new SweetAlertDialog(TireTransfer_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("WARNING")
                                        .setContentText("The specified quantity is too high.")
                                        .show();

                                break;


                            } else {
                                list_label.get(i).setQty(edt_qty.getText().toString());
                                if(edit_qty<item_qty)
                                {
                                    list_label.get(i).setStatus("NG");
                                }
                                else
                                {
                                    list_label.get(i).setStatus("OK");

                                }


                            }


                        }


                    }

                    label_adapter = new Tranfer_Adapter(list_label, TireTransfer_Activity.this, TireTransfer_Activity.this);
                    view_data.setAdapter(label_adapter);
                    Log.d(getString(R.string.tag), "set adapter");


                }


            }
        });


        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupLayout4.setVisibility(GONE);
                edt_qty.setText("");
            }
        });

    }


    @Override
    public void onClick(View view) {

        if (view.getId() == R.id.imb_back){
            finish();
        } else if (view.getId() == R.id.btn_confirm) {
                if (!b_confirm) {
                    Block_button();
                    Confirm();

                }
        } else if (view.getId() == R.id.btn_clear) {
            Clear_layout();
        }


//        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();
        list_label.clear();
        txt_ticket_no.setText("");
        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);

            if(map_label.size()==0 && txt_ticket_no.getText().toString().equals(""))
            {

                txt_ticket_no.setText(data);

            }
            else
            {

                Label_Inquiry(data);

            }

            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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



    private void Label_Inquiry(String bc_tire) {

        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "BC_TIRE/DETAIL");
            json.put("bc_tire", bc_tire);



            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){
//                            new SweetAlertDialog(StocktakingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                    .setTitleText("WARNING")
//                                    .setContentText("Label not found!")
//                                    .show();
                        }else {

                            String id_label = jArray.getJSONObject(0).getString("bc_tire").trim();
                            Log.d(getString(R.string.tag), "response: " + id_label);
                            //check duplicate label in map
                            if (map_label.containsKey(id_label)) {
                                new SweetAlertDialog(TireTransfer_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 {
//

                                String idno = jArray.getJSONObject(0).getString("lbl_part_no").trim()+"|"+jArray.getJSONObject(0).getString("bc_tire");
                                map_label.put(idno, new Tranfer_list(
                                        jArray.getJSONObject(0).getString("id").trim(),
                                        jArray.getJSONObject(0).getString("lbl_part_no").trim(),
                                        jArray.getJSONObject(0).getString("bc_tire").trim(),
                                        jArray.getJSONObject(0).getString("stock_qty").trim(),
                                        jArray.getJSONObject(0).getString("status_data").trim()));

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

        }catch (JSONException e) {
            new SweetAlertDialog(TireTransfer_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);
            Tranfer_list item = map_label.get(key);
            list_label.add(new Tranfer_list(
                    String.valueOf(no),
                    item.getPart_no(),
                    item.getBc_tire(),
                    item.getQty(),
                    item.getStatus()));//location





            Log.d(getString(R.string.tag),"getLabel_id"+ String.valueOf(item.getId()));
        }
        label_adapter = new Tranfer_Adapter(list_label, TireTransfer_Activity.this,TireTransfer_Activity.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);
            }
        }
    }



    @Override
    public void onClickRow(String id, String part_no, String bc_tire, String qty, String status) {

    }

    @Override
    public void SelectionItemRow(String id, String part_no, String bc_tire, String qty, String status) {

        popupLayout4.setVisibility(VISIBLE);
        if (popupLayout4.getVisibility() == VISIBLE) {

            edt_qty.setText("");

            edt_qty.setInputType(InputType.TYPE_NULL);
            edt_qty.requestFocus();

            //bc_tire=ticket_no
            //id = location_no

            str_id = part_no + bc_tire;

            if(qty.equals(".00") || qty.equals(""))
            {
                qty="0";
            }
            txt_qty_total.setText("/"+qty.replace(".00",""));





        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode >= KeyMapping.P1.getId()
                && keyCode <= KeyMapping.P4.getId())
        {

            if (popupLayout4.getVisibility() == VISIBLE) {
                switch (KeyMapping.fromId(keyCode)) {
                    case P1:

                        btn_cancel.performClick();
                        break;

                }
            }
            else {
                switch (KeyMapping.fromId(keyCode)) {
                    case P1:
                        finish();
                        break;

                    case P3:
                        Clear_layout();
                        break;

                    case P4://confirm
                        if (b_confirm == false) {
                            Block_button();
                            Confirm();

                        }
                        break;
                }
            }
        }

        return super.onKeyUp(keyCode, event);
    }

    private void Confirm() {
        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), "Confirm Tire Transfer");
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "SAVE/TIRE_TRANSFER");

            JSONArray jsonArray = new JSONArray();
            for (String key : map_label.keySet()) {

                Tranfer_list item = map_label.get(key);

                Map<String, String> jsonParams = new HashMap<>();
                jsonParams.put("id", item.getId());
                jsonParams.put("item_id", item.getPart_no());
                jsonParams.put("ticket_no", txt_ticket_no.getText().toString());
                jsonParams.put("bc_tire", item.getBc_tire());
                if (item.getStatus().equals("NG")) {
                    jsonParams.put("qty", "0");
                } else {

                    jsonParams.put("qty", item.getQty());

                }

                jsonParams.put("status", item.getStatus());
                jsonParams.put("userid", Settings.getLoginUser().getId());

                JSONObject jsonObject = new JSONObject(jsonParams);
                jsonArray.put(jsonObject);
                json.put("value", jsonArray);
                json.put("barcode", txt_ticket_no.getText().toString());

            }

            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 {
                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status");

                        if (status.trim().equals("success")) {
                            showSuccess("Insert tire transfer completed!!");
                            Clear_layout();

                        } else {
                            showError("Can't tire transfer!!");

                        }


                    }catch (JSONException e) {
                        e.printStackTrace();
                    }




                }
            }.execute();

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


}