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.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
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.ListView;
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.StocktakingLabel_Adapter;
import com.tomastc.ht_nki.ListData.ItemTicket_list;
import com.tomastc.ht_nki.ListData.Location_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 StocktakingLabel_Activity extends Scanner implements View.OnClickListener,ClickRowQCScheculeDetail {
    TextView txt_user, txt_device, txt_location,txt_no,txt_part_no,txt_ticket_no,txt_t_qty,txt_qty,txt_status,txt_qty_total;
    Button btn_clear, btn_confirm;
    RecyclerView view_data;
    String str_location,txt_location_name;
    Map<String, ItemTicket_list> map_label;
    Calendar calendar;
    boolean b_confirm;
    List<ItemTicket_list> list_label;
    StocktakingLabel_Adapter label_adapter;

    Button btn_ok,btn_cancel;

    EditText edt_qty;
    String  str_id;

    Dialog dialog;


    private RelativeLayout popupLayout4;


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

        b_confirm = false;
        map_label = new LinkedHashMap<>();
        list_label = new ArrayList<ItemTicket_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);

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

        txt_no= (TextView) findViewById(R.id.txt_no);
        txt_part_no= (TextView) findViewById(R.id.txt_part_no);
        txt_ticket_no= (TextView) findViewById(R.id.txt_ticket_no);
        txt_t_qty= (TextView) findViewById(R.id.txt_t_qty);
        txt_qty= (TextView) findViewById(R.id.txt_qty);
        txt_status= (TextView) findViewById(R.id.txt_status);

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

                    Integer sum_t_qty = 0;
                    Integer sum_qty = 0;

                    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).getTicket_no() + list_label.get(i).getItem_id() + list_label.get(i).getLocation_id();


                        if (id.equals(str_id)) {


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

                                new SweetAlertDialog(StocktakingLabel_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());
                                list_label.get(i).setStatus("NG");

                            }


                        }

                        sum_t_qty = sum_t_qty + Integer.parseInt(list_label.get(i).getT_qty());
                        sum_qty = sum_qty + Integer.parseInt(list_label.get(i).getQty());


                    }

                    label_adapter = new StocktakingLabel_Adapter(list_label, StocktakingLabel_Activity.this, StocktakingLabel_Activity.this);
                    view_data.setAdapter(label_adapter);
                    Log.d(getString(R.string.tag), "set adapter");
                    txt_t_qty.setText(String.valueOf(sum_t_qty));
                    txt_qty.setText(String.valueOf(sum_qty));
                    txt_no.setText("1");
                    txt_ticket_no.setText("-");
                    txt_part_no.setText("-");

                }


            }
        });


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


        txt_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                search_location();
            }
        });

    }


    private void search_location() {
        // Initialize dialog
        dialog = new Dialog(StocktakingLabel_Activity.this);
        dialog.setContentView(R.layout.dialog_searchable_spinner);
        dialog.getWindow().setLayout(300,300);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();
        // Initialize and assign variable
        EditText editText=dialog.findViewById(R.id.edit_text);
        ListView listView=dialog.findViewById(R.id.list_view);

        // Initialize array adapter
        ArrayAdapter<String> adapter=new ArrayAdapter<>
                (StocktakingLabel_Activity.this, android.R.layout.simple_list_item_1,Settings.getList_location());

        // set adapter
        listView.setAdapter(adapter);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                adapter.getFilter().filter(s);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String location = adapter.getItem(position);

                if (Settings.getMap_location().containsKey(location)){
                    Location_list list = Settings.getMap_location().get(location);
                    txt_location.setText(location);
                    txt_location_name = list.getName();
                    dialog.dismiss();
                }

            }
        });
    }
    @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();
                    UpdateStocktaking();
                }
        } 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();
        txt_location.setText("");
        str_location = "";
        label_adapter=null;
        list_label.clear();
        View_data();
        txt_status.setText("");
        txt_status.setBackgroundResource(R.drawable.background_row);

    }

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


            Label_Inquiry(data,txt_location.getText().toString());
            if(map_label.size()==0)
            {
                if (txt_location.getText().toString().trim().equals("")) {
                    str_location = data;
                    if (Settings.getMap_location().containsKey(str_location)){
                        txt_location.setText(str_location);

                    }else {
                        showWarning("Location not found!!");
                    }
                }

            }


            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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

    private void Label_Inquiry(String ticket_no, String location_id) {

        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "LABEL/DETAIL");
            json.put("ticket_no", ticket_no);
            json.put("location_id", location_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){
//                            new SweetAlertDialog(StocktakingLabel_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                    .setTitleText("WARNING")
//                                    .setContentText("Label not found!")
//                                    .show();
                        }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(StocktakingLabel_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 {
//                                if (status_label.trim().equals("2") || status_label.trim().equals("5")) {//check status label
//                                    if (last_location.trim().equals(txt_location.getText().toString().trim())) {//check location


                                        String idno = jArray.getJSONObject(0).getString("ticket_no").trim()+"|"+jArray.getJSONObject(0).getString("location_id");
                                        map_label.put(idno, new ItemTicket_list(
                                                jArray.getJSONObject(0).getString("id").trim(),
                                                jArray.getJSONObject(0).getString("item_id").trim(),
                                                jArray.getJSONObject(0).getString("ticket_no").trim(),
                                                jArray.getJSONObject(0).getString("location_id").trim(),
                                                jArray.getJSONObject(0).getString("lot_no").trim(),
                                                jArray.getJSONObject(0).getString("t_qty").trim(),
                                                jArray.getJSONObject(0).getString("qty").trim(),
                                                jArray.getJSONObject(0).getString("status").trim()));

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

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

    private void View_data() {
        list_label.clear();
        int no = 0;
        Integer sum_t_qty=0;
        Integer sum_qty=0;
        Log.d(getString(R.string.tag),"mapItem"+ String.valueOf(map_label.size()));
        for (String key : map_label.keySet()){
            no = (no + 1);
            ItemTicket_list item = map_label.get(key);
            list_label.add(new ItemTicket_list(
                    String.valueOf(no),
                    item.getItem_id(),
                    item.getTicket_no(),
                    item.getLocation_id(),
                    item.getLot_no(),
                    item.getT_qty(),
                    item.getQty(),
                    item.getStatus()));//location

            sum_t_qty = sum_t_qty + Integer.parseInt(item.getT_qty());
            sum_qty = sum_qty + Integer.parseInt(item.getQty());


            Log.d(getString(R.string.tag),"getLabel_id"+ String.valueOf(item.getId()));
        }
        label_adapter = new StocktakingLabel_Adapter(list_label, StocktakingLabel_Activity.this,StocktakingLabel_Activity.this);
        view_data.setAdapter(label_adapter);
        Log.d(getString(R.string.tag), "set adapter");
        txt_t_qty.setText(String.valueOf(sum_t_qty));
        txt_qty.setText(String.valueOf(sum_qty));
        txt_no.setText("1");
        txt_ticket_no.setText("-");
        txt_part_no.setText("-");


        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", "STOCK/TAKING");

                JSONArray jsonArray = new JSONArray();
                for (Integer i=0;i<list_label.size();i++)
                {
                    Map<String, String> jsonParams = new HashMap<>();
                    jsonParams.put("label_id", list_label.get(i).getId());
                    jsonParams.put("item_id", list_label.get(i).getItem_id());
                    jsonParams.put("ticket_no", list_label.get(i).getTicket_no());
                    jsonParams.put("location_id", txt_location.getText().toString().trim());
                    jsonParams.put("lot_no", list_label.get(i).getLot_no());
                    jsonParams.put("t_qty", list_label.get(i).getT_qty());
                    jsonParams.put("qty", list_label.get(i).getQty());
                    jsonParams.put("status", list_label.get(i).getStatus());
                    jsonParams.put("userid", 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);

                    String status="";
                    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");
                                    status = jArray.getJSONObject(i).getString("status");


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



                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            if (status.trim().equals("success")) {
                                showSuccess("Insert stocktaking completed!!");
                                Integer sum_t_qty=0;
                                Integer sum_qty=0;

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

                                    if(!list_label.get(i).getStatus().equals("NG"))
                                    {
                                        list_label.get(i).setStatus("OK");
                                    }


                                }

                                label_adapter = new StocktakingLabel_Adapter(list_label, StocktakingLabel_Activity.this,StocktakingLabel_Activity.this);
                                view_data.setAdapter(label_adapter);
                                txt_status.setText("OK");
                                txt_status.setBackgroundResource(R.color.green);

                            }


                        }
                    }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())
        {
            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();
                            UpdateStocktaking();
                        }
                        break;
                }
            }
        }

        return super.onKeyUp(keyCode, event);
    }

    @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(View.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 = bc_tire + part_no + id;

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





        }


    }
}