package com.tomas.ht_mast;

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.Spinner;
import android.widget.TextView;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.ht_mast.ListData.Location_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.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.HashMap;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class Stocktaking_Activity extends Scanner implements View.OnClickListener {
    TextView txt_user, txt_device, txt_part_no, txt_part_name, txt_stock_qty, txt_control_unit, txt_control_unit2, txt_location;
//    Spinner spinner_location;
    ArrayList<String> item_location;
    EditText edt_lot_no, edt_actual_qty;
    String str_lot_no, l_location, l_part_no, str_date, str_serial_no, str_part_no, new_location_name;
    Button btn_confirm, btn_clear;
    Calendar calendar;
    SimpleDateFormat date_lot_no;
    DecimalFormat decimalFormat;
    Dialog dialog;

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

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

        item_location = new ArrayList<String>();
        decimalFormat = new DecimalFormat("#,#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_part_no = (TextView) findViewById(R.id.txt_part_no);
        txt_part_name = (TextView) findViewById(R.id.txt_part_name);
        txt_stock_qty = (TextView) findViewById(R.id.txt_stock_qty);
        txt_control_unit = (TextView) findViewById(R.id.txt_control_unit);
        txt_control_unit2 = (TextView) findViewById(R.id.txt_control_unit2);
        txt_location = (TextView)findViewById(R.id.txt_location);
        txt_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                search_location();
            }
        });


        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(Stocktaking_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();
            }
        });
        edt_actual_qty = (EditText) findViewById(R.id.edt_actual_qty);

//        spinner_location = (Spinner) findViewById(R.id.spinner_location);
//        spinner_location.setEnabled(false);

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

//        Get_Location();

    }

    private void search_location() {
            // Initialize dialog
            dialog = new Dialog(Stocktaking_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<>
                    (Stocktaking_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);
                        new_location_name = list.getName();
                        dialog.dismiss();
                    }

                    Log.d(getString(R.string.tag), "new_location_name:" + new_location_name);
                }
            });
    }

//    private void Get_Location() {
//        item_location.clear();
//        try {
//            JSONObject json = new JSONObject();
//            json.put("cmd", "list");
//
//
//            new AsyncHttpClient(getApplicationContext(),
//                    Settings.getMgmtList().get("web_api") + "/location_master.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);
//                        for(int i=0;i<jArray.length();i++) {
//                            item_location.add(
//                                    jArray.getJSONObject(i).getString("id")
//                            );
//                        }
//                        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
//                                (getApplicationContext(), R.layout.spinner_list, item_location);
//                        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//                        spinner_location.setAdapter(dataAdapter);
//
//                        Log.d(getString(R.string.tag), String.valueOf(item_location.size()));
//                    }catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }.execute();
//
//        }catch (JSONException e) {
//            e.printStackTrace();
//        }
//    }

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

            case R.id.btn_confirm:
                ButtonClick_Confirm();

                break;

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

    private void ButtonClick_Confirm() {
        if (txt_part_no.getText().toString().equals("")
                ||edt_actual_qty.getText().toString().equals("")
                ||txt_stock_qty.getText().toString().equals("")
                ||edt_lot_no.getText().toString().equals("")){
            new SweetAlertDialog(Stocktaking_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Please complete the information")
                    .show();
        }else{
            Check_Qty();
        }
    }

    private void Check_Qty() {
        Double f_qty = 0.0, f_act_qty = 0.0;
        String str_qty = txt_stock_qty.getText().toString().trim().replaceAll(",","");
        String str_act_qty = edt_actual_qty.getText().toString().trim();

        f_qty = Double.parseDouble(str_qty);
        f_act_qty = Double.parseDouble(str_act_qty);
        if (!Utils.CompareDouble(f_qty , f_act_qty)){
            new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Is it okay if the quantities do not match?")
                    .setCancelText("No")
                    .showCancelButton(true)
                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.cancel();
                        }
                    })
                    .setConfirmText("Yes")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.cancel();
                            //sent to save....
                            UpdateStocktaking();
                        }
                    })
                    .show();

        }else {
            UpdateStocktaking();
        }
    }

    private void reset_view() {
        btn_confirm.setEnabled(false);
        btn_confirm.setBackgroundResource(R.drawable.button_background_gray);
        btn_clear.setEnabled(false);
        btn_clear.setBackgroundResource(R.drawable.button_background_gray);
        edt_actual_qty.setEnabled(false);

        txt_part_no.setText("");
        txt_part_name.setText("");
        edt_lot_no.setText("");
        edt_actual_qty.setText("");
        txt_location.setText("");
        txt_stock_qty.setText("");
        txt_control_unit.setText("");
        txt_control_unit2.setText("");

        new_location_name = "";
    }

    @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 == 7){
                txt_location.setEnabled(true);
                str_part_no = tokens[1];
                str_serial_no= tokens[6];
                str_lot_no = tokens[3];
                txt_part_no.setText(str_part_no);
                edt_lot_no.setText(str_lot_no);
                getLabelDetail();

            }else if (tokens.length == 3){//scan location
                String[] tokens_lo = data.split(getString(R.string.DELIMITER_SCAN_TOKEN),-1);
                Log.d(getString(R.string.tag), Arrays.deepToString(tokens_lo));
                l_location = tokens_lo[0].trim();
                l_part_no = tokens_lo[1].trim();

                if (Settings.getMap_location().containsKey(l_location)){
                    Location_list list = Settings.getMap_location().get(l_location);
                    txt_location.setText(l_location);
                    new_location_name = list.getName();
                    Log.d(getString(R.string.tag), "new_location_name:" + new_location_name);
                }else {
                    new SweetAlertDialog(Stocktaking_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("WARNING")
                            .setContentText("not found location!")
                            .show();
                }
            }else {
                showWarning("Invalid QR code!!");
            }

            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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

    private void getLabelDetail() {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "LABEL/STOCK/SUMMARY");
            json.put("parts_no", str_part_no);
            json.put("lot_no", str_lot_no);
            json.put("serial_no", str_serial_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() != 1) {
                            showWarning("Label data not found!!");
                            return;
                        }
                        JSONObject label = jArray.getJSONObject(0);

                        // Check label status
                        if (
                                label.getInt("status")!=2 // IN_STORE
                        ) {
                            showWarning("Invalid label status!!");
                            return;
                        }
                        txt_part_no.setText(label.getString("lbl_part_no").trim());
                        txt_part_name.setText(label.getString("lbl_part_name").trim());
                        txt_control_unit.setText(label.getString("control_unit").trim());
                        txt_control_unit2.setText(label.getString("control_unit").trim());
                        txt_stock_qty.setText(decimalFormat.format(Double.parseDouble(label.getString("qty"))));
                        edt_actual_qty.setText(label.getString("qty"));
                        edt_actual_qty.setEnabled(true);
                        txt_location.setText(label.getString("last_location_id").trim());
//                        spinner_location.setSelection(item_location.indexOf(label.getString("last_location_id")));

                        btn_confirm.setEnabled(true);
                        btn_confirm.setBackgroundResource(R.drawable.button_background_blue);
                        btn_clear.setEnabled(true);
                        btn_clear.setBackgroundResource(R.drawable.button_background_yellow);
                    }catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }.execute();

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

    private void UpdateStocktaking() {
        calendar = Calendar.getInstance();
        SimpleDateFormat date_time = new SimpleDateFormat("yyyyMM");
        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", "add");

            JSONArray jsonArray = new JSONArray();
            Map<String, String> jsonParams = new HashMap<>();
            jsonParams.put("item_id",txt_part_no.getText().toString().trim());
            jsonParams.put("location_id",txt_location.getText().toString().trim());
            jsonParams.put("lot_no",edt_lot_no.getText().toString().trim());
            jsonParams.put("taking_month",str_date);
            jsonParams.put("stocktaking",edt_actual_qty.getText().toString().trim());
            jsonParams.put("stocktaking_status","0");
            jsonParams.put("qty",txt_stock_qty.getText().toString().replaceAll(",",""));
            jsonParams.put("control_unit",txt_control_unit.getText().toString());
            jsonParams.put("update_user_id",Settings.getLoginUser().getId());
            //serial_no
            //label_id

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

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/stocktaking.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");
                        int affected_rows = jsonObject.getInt("affected_rows");

                        if (status.equals("success")){
                            if (affected_rows > 0){
                                showSuccess("Stocktaking data saved.");
                                reset_view();
                            }else {
                                showWarning("Stocktaking data duplicated!!");
                            }
                        }else{
                            showError("Can't register stocktaking data!!");
                        }
                    }catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }.execute();

        } catch (Exception e) {
            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:
                    finish();
                    break;

                case P3:
                    reset_view();
                    break;

                case P4://confirm
                    ButtonClick_Confirm();
                    break;
            }
        }

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