package com.tomas.ht_mast;

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 android.app.DatePickerDialog;
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.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.ht_mast.Adapter.ItemStock_Adapter;
import com.tomas.ht_mast.Adapter.ScheduleLabel_Adapter;
import com.tomas.ht_mast.ListData.ItemMaster_list;
import com.tomas.ht_mast.ListData.ItemStock_list;
import com.tomas.ht_mast.lib.KeyMapping;
import com.tomas.ht_mast.lib.Scanner;
import com.tomas.ht_mast.lib.Settings;
import com.tomas.ht_mast.lib.common.AsyncHttpClient;
import com.tomas.ht_mast.lib.common.DatetimeUtil;
import com.tomas.ht_mast.lib.common.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class StockCheck_Activity extends Scanner implements View.OnClickListener {

    TextView txt_user, txt_device, txt_parts_no, txt_total;
    EditText edt_lot_no;
    Button btn_clear, btn_ok;
    Calendar calendar;
    Dialog dialog;
    SimpleDateFormat date_lot_no;
    String str_lot_no;
    List<ItemStock_list>list_item;
    RecyclerView view_data;
    ItemStock_Adapter itemStock_adapter;
    DecimalFormat decimalFormat;
    Double sum_total =0.0;

    @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("#,#00.00");

        calendar = Calendar.getInstance();
        date_lot_no = new SimpleDateFormat("yyyy-MM-dd");

        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_parts_no = (TextView) findViewById(R.id.txt_part_no);
        txt_parts_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                search_part();
            }
        });
        txt_total = (TextView) findViewById(R.id.txt_total);

        edt_lot_no = (EditText) findViewById(R.id.edt_lot_no);
        edt_lot_no.setInputType(InputType.TYPE_NULL);
        edt_lot_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final Calendar currentDate = Calendar.getInstance();
                new DatePickerDialog(StockCheck_Activity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        str_lot_no = ( year+"-"+
                                (String.format("%2s",monthOfYear + 1).replace(' ','0'))+"-"+
                                (String.format("%2s",dayOfMonth).replace(' ','0')));
                        edt_lot_no.setText(str_lot_no);
                    }
                }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).show();
            }
        });

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

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

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

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

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

    private void search_part() {
        // Initialize dialog
        dialog = new Dialog(StockCheck_Activity.this);
        dialog.setContentView(R.layout.dialog_searchable_spinner);
        int width = (int)(getResources().getDisplayMetrics().widthPixels*0.90);
        int height = (int)(getResources().getDisplayMetrics().heightPixels*0.90);
        dialog.getWindow().setLayout(width, height);
        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<>
                (StockCheck_Activity.this, android.R.layout.simple_list_item_1, Settings.getList_item());

        // 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 item_code = adapter.getItem(position);
                txt_parts_no.setText(item_code);
                dialog.dismiss();

            }
        });
    }

    private void Check_Stock() {
        list_item.clear();
        sum_total = 0.0;
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "ITEM/STOCK/CHECK");
            json.put("parts_no", txt_parts_no.getText().toString().trim());
            json.put("lot_no", edt_lot_no.getText().toString().trim());

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

                            // 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("item_id"),
                                        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) {
                        e.printStackTrace();
                    }
                }
            }.execute();

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

    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 void processData(String data, DecodeResult.Result result, String codeType) {
        if(data.trim().equals(""))
            return;

        try {
            Log.d(getString(R.string.tag), "data scan: " + data);
            String[] tokens = data.split(getString(R.string.DELIMITER_SCAN_TOKEN),-1);
            Log.d(getString(R.string.tag), Arrays.deepToString(tokens));

            if (tokens.length == 7){
                txt_parts_no.setText(tokens[1].trim());
                edt_lot_no.setText(tokens[3].trim());

                Check_Stock();

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

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

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyMapping.Down.getId() || keyCode == KeyMapping.P2.getId()
                || keyCode == KeyMapping.ENT.getId())
        {
            switch (KeyMapping.fromId(keyCode)) {
                case Down:
                    finish();
                    break;

                case P2:
                    Clear_layout();
                    break;

                case ENT://ok
                    ButtonClick_OK();
                    break;
            }
        }

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