package com.tomastc.ht_nki;

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.TextView;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomastc.ht_nki.ListData.Location_list;
import com.tomastc.ht_nki.lib.AlertProgress;
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.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class ChangeLocation_Activity extends Scanner implements View.OnClickListener {
    TextView txt_user, txt_device,txt_parts_no, txt_parts_name, txt_lot_no
            , txt_old_location, txt_stock_qty, txt_control_unit, txt_control_unit2, txt_new_location;
    EditText edt_actual_qty;
    Button btn_confirm, btn_clear;
    JSONObject first_label = null, second_label = null;
    String str_lot_no, l_location, l_part_no, new_location_name,old_location_name, str_serial_no, str_part_no,str_qty;
    List<String> list_location;
    int LABEL_QTY, PRINT_TIMES;
    AlertProgress alert;
    boolean print_label = false;
    private volatile boolean stopThread = true;
    DecimalFormat decimalFormat;
    Dialog dialog;

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

        stopThread = true;
        second_label = null;
        new_location_name = "";
        list_location = new ArrayList<String>();
        alert = new AlertProgress(ChangeLocation_Activity.this);

        decimalFormat = new DecimalFormat("#,#00.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_parts_no = (TextView) findViewById(R.id.txt_parts_no);
        txt_parts_name = (TextView) findViewById(R.id.txt_parts_name);
        txt_lot_no = (TextView) findViewById(R.id.txt_lot_no);
        txt_old_location = (TextView) findViewById(R.id.txt_old_location);
        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_new_location = (TextView) findViewById(R.id.txt_new_location);

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

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

        edt_actual_qty = (EditText) findViewById(R.id.edt_actual_qty);
        //edt_actual_qty.requestFocus();
        edt_actual_qty.setEnabled(false);
        edt_actual_qty.setShowSoftInputOnFocus(false);
        edt_actual_qty.setInputType(InputType.TYPE_NULL);
        edt_actual_qty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                edt_actual_qty.requestFocus();
            }
        });

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

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

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

    private void search_location_old() {
        // Initialize dialog
        dialog = new Dialog(ChangeLocation_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<>
                (ChangeLocation_Activity.this, android.R.layout.simple_list_item_1,list_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 (list_location.contains(location)){
                    txt_old_location.setText(location);
                    old_location_name = location;
                    first_label=null;
                    reset_view();
                    getLabelDetail(location);
                    dialog.dismiss();

                }




                Log.d(getString(R.string.tag), "old_location_name:" + old_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);



            l_location = data;
            if (Settings.getMap_location().containsKey(l_location)){
                Location_list list = Settings.getMap_location().get(l_location);
                txt_new_location.setText(l_location);
                new_location_name = list.getName();
                Log.d(getString(R.string.tag), "new_location_name:" + new_location_name);
            }else {

                str_part_no = data;
                getLabelDetail("");


            }




            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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

    private void getLabelDetail(String filter_location) {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "LABEL/STOCK/SUMMARY");
            json.put("item_id", str_part_no);
            if(!filter_location.equals(""))
            {
                json.put("filter_location", filter_location);


            }

            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 (first_label == null) {//first scan label
                            for (int i = 0; i < jArray.length(); i++) {
                                try {
                                    JSONObject label = jArray.getJSONObject(0);


                                    first_label = label;
                                    txt_parts_no.setText(label.getString("ticket_no").trim()+"/"+label.getString("lbl_part_no").trim());
                                    txt_parts_name.setText(label.getString("lbl_part_name").trim());
                                    txt_lot_no.setText(label.getString("lot_no").trim());
                                    txt_control_unit.setText(label.getString("control_unit").trim());
                                    txt_control_unit2.setText(label.getString("control_unit").trim());
                                    txt_stock_qty.setText(label.getString("qty"));
                                    edt_actual_qty.setText(label.getString("qty"));
                                    txt_old_location.setText(label.getString("location_id").trim());

                                    if(filter_location.equals("")) {
                                        list_location.add(jArray.getJSONObject(i).getString("location_id"));
                                    }

                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }
                            }



                        }
                        else if (first_label != null) {
                            for (int i = 0; i < jArray.length(); i++) {
                                try {
                                    JSONObject label = jArray.getJSONObject(0);

                                    second_label = label;
                                    txt_control_unit2.setText(label.getString("control_unit"));
                                    edt_actual_qty.setText(label.getString("qty"));
                                    edt_actual_qty.setEnabled(false);





                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }
                            }



                        }


                        btn_clear.setEnabled(true);
                        btn_clear.setBackgroundResource(R.drawable.button_background_yellow);
                        btn_confirm.setEnabled(true);
                        btn_confirm.setBackgroundResource(R.drawable.button_background_blue);


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

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

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

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

            case R.id.imb_back:
                finish();
                break;

        }
    }

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

        txt_parts_no.setText("");
        txt_parts_name.setText("");
        txt_lot_no.setText("");
        txt_stock_qty.setText("");
        txt_control_unit.setText("");
        txt_control_unit2.setText("");
        txt_old_location.setText("");
        edt_actual_qty.setText("");
        edt_actual_qty.setEnabled(true);
        txt_new_location.setEnabled(false);
        new_location_name = "";


        first_label =  null;
        second_label = null;
        print_label = false;

    }

    private void Confirm() {
        Log.d(getString(R.string.tag), "old label: " + first_label.length());
        if (!edt_actual_qty.getText().toString().trim().equals("") && !edt_actual_qty.getText().toString().trim().equals("0") && !txt_new_location.getText().toString().trim().equals("") ){
            if (second_label == null){
                //check move qty != stock qty

                Double stock_qty = Double.parseDouble(txt_stock_qty.getText().toString().trim().replaceAll(",",""));
                Double move_qty = Double.parseDouble(edt_actual_qty.getText().toString().trim());
                if (move_qty > stock_qty){
                    print_label = false;
                    new SweetAlertDialog(ChangeLocation_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("WARNING")
                            .setContentText("Move qty error!!")
                            .show();
                    return;
                }else {
                    print_label = true;
                }
            }

            new SweetAlertDialog(ChangeLocation_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Click YES to confirm the location change?")
                    .setCancelText("No")
                    .showCancelButton(true)
                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.dismiss();
                        }
                    })
                    .setConfirmText("Yes")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.dismiss();

                            MoveAllLocation();
                        }
                    })
                    .show();
        }else {

            new SweetAlertDialog(ChangeLocation_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Please complete the information!")
                    .show();
        }
    }

    private void MoveAllLocation() {
        Log.d(getString(R.string.tag), "MoveAllLocation: " );
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "CHANGE/LOCATION");
            Map<String, String> jsonParams;

            // Inbound
            JSONArray jArray = new JSONArray();
            jsonParams = new HashMap<>();
            jsonParams.put("item_id", first_label.getString("lbl_part_no"));
            jsonParams.put("item_name", first_label.getString("lbl_part_name").trim());
            jsonParams.put("ticket_no", first_label.getString("ticket_no").trim());
            jsonParams.put("lot_no", first_label.getString("lot_no"));
            jsonParams.put("location_id", first_label.getString("location_id"));
            jsonParams.put("location_name", Settings.getMap_location().get(first_label.getString("location_id").trim()).getName());
            jsonParams.put("new_location_id", txt_new_location.getText().toString().trim());
            jsonParams.put("new_location_name",new_location_name);
            jsonParams.put("move_qty",edt_actual_qty.getText().toString());
            jsonParams.put("user_id", Settings.getLoginUser().getId());
            JSONObject jsonObject = new JSONObject(jsonParams);
            jArray.put(jsonObject);
            json.put("value",jArray);

            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.equals("success")){
                            Log.d(getString(R.string.tag), "new label: " + response);
                            reset_view();

                            showSuccess("Change location completed.");

                        } else {
                            showError("Change location failed[" + jsonObject.getString("error") + "]!!");
                        }

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

                }
            }.execute();

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












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

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