package com.tomas.ht_mast;

import static com.tomas.ht_mast.lib.KeyMapping.P1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.tomas.ht_mast.ListData.Factory_list;
import com.tomas.ht_mast.ListData.ItemMaster_list;
import com.tomas.ht_mast.ListData.Location_list;
import com.tomas.ht_mast.ListData.PackingStandard_list;
import com.tomas.ht_mast.ListData.Supplier_list;
import com.tomas.ht_mast.lib.AlertProgress;
import com.tomas.ht_mast.lib.KeyMapping;
import com.tomas.ht_mast.lib.Settings;
import com.tomas.ht_mast.lib.common.AsyncHttpClient;

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

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class MainMenu_Activity extends AppCompatActivity implements View.OnClickListener {
    TextView txt_user, txt_device;
    Map<String, Factory_list>map_factory;
    List<String>list_factory;
    Map<String, Location_list> map_location;
    List<String> list_location;
    Map<String, Supplier_list>map_supplier;
    List<String>list_supplier;
    Map<String, ItemMaster_list>map_item;
    List<String>list_item;
    List<String>sub_item;
    Map<String, PackingStandard_list>map_packing;
    DecimalFormat decimalFormat;
    AlertProgress alert;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        map_supplier = new LinkedHashMap<>();
        map_item = new LinkedHashMap<>();
        map_location = new LinkedHashMap<>();
        map_packing = new LinkedHashMap<>();
        map_factory = new LinkedHashMap<>();
        sub_item = new ArrayList<>();
        list_item = new ArrayList<>();
        list_supplier = new ArrayList<>();
        list_location = new ArrayList<>();
        list_factory = new ArrayList<>();
        decimalFormat = new DecimalFormat("##0.00");

        alert = new AlertProgress(MainMenu_Activity.this);

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

        Location_Master();
        Items_Master();
        Supplier_Master();
        PackingStandard_Master();
        Factory_Master();
    }


    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.btn_inbound:
                intent = new Intent(MainMenu_Activity.this, InboundMenu_Activity.class);
                startActivity(intent);
                break;

            case R.id.btn_outbound:
                intent = new Intent(MainMenu_Activity.this, OutbountMenu_Activity.class);
                startActivity(intent);
                break;

            case R.id.btn_stock_management:
                intent = new Intent(MainMenu_Activity.this, StockMenu_Activity.class);
                startActivity(intent);
                break;

            case R.id.btn_printer_setting:
                intent = new Intent(MainMenu_Activity.this, PrinterSetting_Activity.class);
                startActivity(intent);
                break;

            case R.id.btn_close:
                finishAffinity();
                System.exit(0);
                break;
        }
    }
    private void Location_Master() {
        list_location.clear();
        map_location.clear();
        alert.setMessage("           Loading environment....         ");
        alert.show();
        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), "Location response: " + response);

                    try{
                        JSONArray jArray = new JSONArray(response);
                        for(int i=0;i<jArray.length();i++) {

                            list_location.add(jArray.getJSONObject(i).getString("id").trim());
                            map_location.put(jArray.getJSONObject(i).getString("id").trim(),
                                    new Location_list(
                                            jArray.getJSONObject(i).getString("id").trim(),
                                            jArray.getJSONObject(i).getString("name").trim() == "null" ? "" : jArray.getJSONObject(i).getString("name").trim(),
                                            jArray.getJSONObject(i).getString("factory_code").trim()== "null" ? "" : jArray.getJSONObject(i).getString("factory_code").trim(),
                                            "",
                                            jArray.getJSONObject(i).getString("description").trim()== "null" ? "" : jArray.getJSONObject(i).getString("description").trim(),
                                            jArray.getJSONObject(i).getString("qc_area").trim()));
                        }
                        Settings.setMap_location(map_location);
                        Settings.setList_location(list_location);
                        alert.dismiss();
                    }catch (JSONException e) {
                        alert.dismiss();
                        new SweetAlertDialog(MainMenu_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void Items_Master() {
        map_item.clear();
        list_item.clear();
        alert.setMessage("           Loading environment....         ");
        alert.show();
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "list");

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/item_master.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "Items response: " + response);

                    try{
                        sub_item.add("All");
                        JSONArray jArray = new JSONArray(response);
                        for(int i=0;i<jArray.length();i++) {
                            String item_code = jArray.getJSONObject(i).getString("id").trim();
                            String item_name = jArray.getJSONObject(i).getString("name").trim();
                            String location = jArray.getJSONObject(i).getString("location_fix_id").trim();
                            String control_unit = jArray.getJSONObject(i).getString("control_unit").trim();

                            map_item.put(item_code, new ItemMaster_list(item_code, item_name, location, control_unit));
                            list_item.add(item_code);
                            sub_item.add(item_code.substring(4, 11).trim());

                        }

                        Settings.setMap_items(map_item);
                        Settings.setList_item(list_item);

                        List<String> result = new ArrayList<>();
                        result = sub_item.stream()
                                .distinct()
                                .collect(Collectors.toList());

                        Settings.setSub_item(result);

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

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

    private void Supplier_Master() {
        map_supplier.clear();
        list_supplier.clear();
        alert.setMessage("           Loading environment....         ");
        alert.show();
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "list");
            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/supplier_master.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "Supplier response: " + response);

                    try{
                        JSONArray jArray = new JSONArray(response);
                        list_supplier.add("All");
                        map_supplier.put("All", new Supplier_list("All","",""));

                        for(int i=0;i<jArray.length();i++) {
                            list_supplier.add(jArray.getJSONObject(i).getString("id").trim()+"  "+jArray.getJSONObject(i).getString("alias").trim());

//                            map_supplier.put(jArray.getJSONObject(i).getString("id").trim()+"  "+jArray.getJSONObject(i).getString("alias").trim(),
                            map_supplier.put(jArray.getJSONObject(i).getString("id").trim(),
                                    new Supplier_list(jArray.getJSONObject(i).getString("id").trim(),
                                            jArray.getJSONObject(i).getString("name").trim() == "null" ? "" : jArray.getJSONObject(i).getString("name").trim(),
                                            jArray.getJSONObject(i).getString("alias")));
                        }

                        Settings.setMap_supplier(map_supplier);
                        Settings.setList_supplier(list_supplier);
                        alert.dismiss();
                    }catch (JSONException e) {
                        alert.dismiss();
                        new SweetAlertDialog(MainMenu_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void PackingStandard_Master() {
        map_packing.clear();
        alert.setMessage("           Loading environment....         ");
        alert.show();
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "list");

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/packing_standard_master.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "PackingStandard response : " + response);

                    try{
                        JSONArray jArray = new JSONArray(response);
                        for(int i=0;i<jArray.length();i++) {
                           String packing_id = jArray.getJSONObject(i).getString("package_id");

                           if (packing_id.trim().equals("BOX")) {
                               map_packing.put(jArray.getJSONObject(i).getString("item_id"),
                                       new PackingStandard_list(
                                               jArray.getJSONObject(i).getString("item_id"),
                                               jArray.getJSONObject(i).getString("package_id"),
                                               String.valueOf(decimalFormat.format(jArray.getJSONObject(i).getInt("qty"))),
                                               jArray.getJSONObject(i).getString("unit_qty")));
                           }
                        }

                        Settings.setMap_packing(map_packing);
                        Log.d(getString(R.string.tag), String.valueOf(map_packing.size()));
                        alert.dismiss();
                    }catch (JSONException e) {
                        alert.dismiss();
                        new SweetAlertDialog(MainMenu_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void Factory_Master() {
        map_factory.clear();
        list_factory.clear();
        alert.setMessage("           Loading environment....         ");
        alert.show();
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "FACTORY_CODE/LIST");
            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);
                        list_factory.add("All");
                        for(int i=0;i<jArray.length();i++) {
                            list_factory.add( jArray.getJSONObject(i).getString("factory_code").trim());

                            map_factory.put( jArray.getJSONObject(i).getString("factory_code").trim(),
                                    new Factory_list(jArray.getJSONObject(i).getString("factory_code").trim()));
                        }

                        Settings.setMap_factory(map_factory);
                        Settings.setList_factory(list_factory);
                        alert.dismiss();
                    }catch (JSONException e) {
                        alert.dismiss();
                        new SweetAlertDialog(MainMenu_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    @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:
                    finishAffinity();
                    System.exit(0);
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        finishAffinity();
        System.exit(0);
    }
}