package com.tomas.ht_ydt;

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
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.ImageButton;
import android.widget.ListView;
import android.widget.SearchView;
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.tomas.ht_ydt.Adapter.ItemStock_Adapter;
import com.tomas.ht_ydt.ListData.ItemStock_list;
import com.tomas.ht_ydt.ListData.Item_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.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class StockCheck_Activity extends Scanner implements View.OnClickListener {
    TextView txt_part_no, txt_total, txt_user, txt_device;
    RecyclerView view_data;
    Dialog dialog_search;
    String str_part_no;
    Double sum_total = 0.0;
    List<ItemStock_list> list_item;
    DecimalFormat decimalFormat;
    ItemStock_Adapter itemStock_adapter;
    Button btn_clear, btn_ok;
    ImageButton imb_back;

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

        list_item = new ArrayList<ItemStock_list>();
        decimalFormat = new DecimalFormat("#,##0.00");

        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_total = (TextView) findViewById(R.id.txt_total);
        txt_total.setText("0.00");
        txt_part_no = (TextView) findViewById(R.id.txt_part_no);
        txt_part_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                search_items();
            }
        });

        btn_ok = (Button)findViewById(R.id.btn_ok);
        btn_clear = (Button)findViewById(R.id.btn_clear);
        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());

    }


    private void search_items() {
        // Initialize dialog
        dialog_search = new Dialog(StockCheck_Activity.this);
        dialog_search.setContentView(R.layout.dialog_search);
        dialog_search.getWindow().setLayout(300, 300);
        dialog_search.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog_search.show();
        // Initialize and assign variable
        SearchView searchView = dialog_search.findViewById(R.id.search);
        ListView listView = dialog_search.findViewById(R.id.listView);

        final SearchMyAdapter adapter = new SearchMyAdapter(this, Settings.getData_part_no(), new ItemClickListener_Search() {
            @Override
            public void OnItemClicked(String item_code) {
                txt_part_no.setText(item_code);
                if (Settings.getMap_item().containsKey(item_code)){
                    Item_list item = Settings.getMap_item().get(item_code);
                    str_part_no = item.getItem_code();
                    txt_part_no.setText(str_part_no);
                    Check_Stock(str_part_no);
                }
                dialog_search.dismiss();
            }
        });
        listView.setAdapter(adapter);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                adapter.getFilter().filter(newText);
                return false;
            }
        });
    }

    @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_ok:
                ButtonClick_OK();
                break;

        }
    }

    private void ButtonClick_OK() {
        if (txt_part_no.getText().toString().equals("")){
            new SweetAlertDialog(StockCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Please complete the information")
                    .show();
        }else{
            Check_Stock(str_part_no);
        }
    }


    private void Clear_Layout() {
        txt_part_no.setText("");
        txt_total.setText("0.00");
        sum_total = Double.parseDouble("0");
        list_item.clear();
        ViewData();
    }

    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
        if (data.trim().equals(""))
            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){
                str_part_no = tokens[0].trim();
                Check_Stock(str_part_no);
            }else {
                new SweetAlertDialog(StockCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Invalid QR code!")
                        .show();
            }
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);
        } catch (Exception e) {
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
        }

    }

    private void Check_Stock(String part_no) {
        list_item.clear();
        sum_total = 0.0;
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "ITEM/STOCK/CHECK");
            json.put("parts_no", part_no);

            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) {
                            txt_part_no.setText("");
                            showWarning("Stock data not found!!");
                        }else {
                            txt_part_no.setText(part_no);
                            // Load response data to table view
                            for (int i = 0; i < jArray.length(); i++) {
                                list_item.add(new ItemStock_list(
                                        String.valueOf(i+1),
                                        jArray.getJSONObject(i).getString("id"),
                                        jArray.getJSONObject(i).getString("lot_no"),
                                        jArray.getJSONObject(i).getString("location_id"),
                                        jArray.getJSONObject(i).getString("label_count"),
                                        jArray.getJSONObject(i).getString("qty")));

                                Double qty = 0.0;
                                String str_qty =  jArray.getJSONObject(i).getString("qty");
                                qty = Double.valueOf(str_qty);
                                sum_total = (sum_total + qty);
                            }
                        }
                        ViewData();

                    }catch (JSONException e) {
                        showError(e.getMessage());
                    }
                }
            }.execute();

        }catch (JSONException e) {
            showError(e.getMessage());
        }
    }

    private void ViewData() {
        txt_total.setText(String.valueOf(decimalFormat.format(sum_total)));
        itemStock_adapter = new ItemStock_Adapter(list_item, this);
        view_data.setAdapter(itemStock_adapter);
    }

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

        return super.onKeyUp(keyCode, event);
    }

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