package com.tomas.ht_mast;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
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.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.ht_mast.Adapter.ScheduleLabel_Adapter;
import com.tomas.ht_mast.Adapter.ScheduleOutbound_Adapter;
import com.tomas.ht_mast.ListData.ItemMaster_list;
import com.tomas.ht_mast.ListData.PackingStandard_list;
import com.tomas.ht_mast.ListData.ScheduleLabel_Item;
import com.tomas.ht_mast.ListData.ScheduleOutbound_Item;
import com.tomas.ht_mast.ListData.Supplier_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.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class LabelSchedule_Activity extends Scanner implements View.OnClickListener {
    EditText edt_date_from, edt_date_to;
//    CheckBox checkBox;
    Dialog dialog;
    RecyclerView view_schedule;
    Calendar calendar, calendar_from, calendar_to;
    SimpleDateFormat date;
    DecimalFormat decimalFormat;
    SwipeRefreshLayout swipeContainer;
    List<ScheduleLabel_Item> list_item;
    Map<String, ScheduleLabel_Item> map_sch_item;
    ScheduleLabel_Adapter adapter_label;

    TextView txt_supplier, txt_part_no;
    String str_date_from, str_date_to;
    Spinner spinner_status;

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

        decimalFormat = new DecimalFormat("##0.00");

        list_item = new ArrayList<ScheduleLabel_Item>();
        map_sch_item = new LinkedHashMap<>();

        calendar = Calendar.getInstance();
        calendar_from = Calendar.getInstance();
//        calendar_from.add(Calendar.DATE, -7);
        calendar_to = Calendar.getInstance();
//        calendar_to.add(Calendar.DATE, +7);
        date = new SimpleDateFormat("yyyy-MM-dd");
        str_date_from = date.format(calendar_from.getTime());
        str_date_to = date.format(calendar_to.getTime());

        spinner_status = (Spinner)findViewById(R.id.spinner_status);
        txt_part_no = (TextView)findViewById(R.id.txt_part_no);
        txt_part_no.setText("All");
        txt_part_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                search_part();
            }
        });

        txt_supplier = (TextView) findViewById(R.id.txt_supplier);
        txt_supplier.setText("All");
        txt_supplier.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                search_supplier();
            }
        });

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

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

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

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

        swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
        swipeContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(getString(R.string.tag), "swipeContainer click:" + "click");
            }
        });
        swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipeContainer.setRefreshing(false);
                        Load_Schedule();
                    }
                },2000);
            }
        });

        swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);

        view_schedule = (RecyclerView) findViewById(R.id.view_schedule);
        view_schedule.setHasFixedSize(true);
        view_schedule.setRecycledViewPool(new RecyclerView.RecycledViewPool());
        view_schedule.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        view_schedule.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        view_schedule.setItemAnimator(new DefaultItemAnimator());
    }




    @Override
    protected void onStart() {
        super.onStart();
        Load_Schedule();
    }

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

    @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);
            if (Settings.getMap_supplier().containsKey(data.trim())){
                txt_supplier.setText(data.trim());

            }else{
                new SweetAlertDialog(LabelSchedule_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 search_part() {
        // Initialize dialog
        dialog = new Dialog(LabelSchedule_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<>
                (LabelSchedule_Activity.this, android.R.layout.simple_list_item_1, Settings.getSub_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_part_no.setText(item_code);
                dialog.dismiss();

                if (item_code.trim().equals("All")){
                    Load_Schedule();
                }else {
                    set_view_data();
                }
            }
        });
    }

    private void search_supplier() {
        // Initialize dialog
        dialog = new Dialog(LabelSchedule_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<>
                (LabelSchedule_Activity.this, android.R.layout.simple_list_item_1,Settings.getList_supplier());

        // 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 supplier = adapter.getItem(position);
                if (!supplier.trim().equals("All")) {
                    supplier = supplier.substring(0, 5);

                    Log.d(getString(R.string.tag), "supplier: " +supplier);
                    if (Settings.getMap_supplier().containsKey(supplier)){
                        txt_supplier.setText(supplier);
                        dialog.dismiss();
                    }
                }else {
                    txt_supplier.setText(supplier);
                    dialog.dismiss();
                }
            }
        });
    }
    private void Load_Schedule() {
        try {//check date from-to

            String Supplier = "";
            if (txt_supplier.getText().toString().trim().equals("All")){
                Supplier = "";
            }else {
                Supplier = txt_supplier.getText().toString().trim();
            }

            Date date_from = date.parse(str_date_from);
            Date date_to = date.parse(str_date_to);
            Log.d(getString(R.string.tag), "check date from-to: " + str_date_from+"-"+str_date_to);

            if (date_to.before(date_from)) {
                new SweetAlertDialog(LabelSchedule_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Selected incorrect date")
                        .show();
            }else {
                map_sch_item.clear();
                try {
                    JSONObject json = new JSONObject();
                    json.put("cmd", "SCHEDULE/LABEL");
                    json.put("action_plan_date_from", str_date_from);
                    json.put("action_plan_date_to", str_date_to);
                    json.put("supplier",Supplier);
                    json.put("incharge", Settings.getLoginUser().getDepartment());
                    json.put("except_complete", spinner_status.getSelectedItem().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{
                                JSONObject jsonObject = new JSONObject(response);
                                String value = jsonObject.getString("value");
                                JSONArray jArray = new JSONArray(value);

                                if (jArray.length() == 0){
                                    Toast.makeText(LabelSchedule_Activity.this, "Not found schedule", Toast.LENGTH_SHORT).show();
                                }else {
                                    for(int i = 0; i < jArray.length(); i++){
                                        JSONObject obj = jArray.getJSONObject(i);
                                        JSONObject order_date = obj.getJSONObject("order_dt");
                                        String str_order_date = order_date.getString("date");
                                        str_order_date = str_order_date.substring(0,10);
                                        Log.d(getString(R.string.tag), "str_order_date: " + str_order_date);

                                        map_sch_item.put(jArray.getJSONObject(i).getString("id"),
                                                new ScheduleLabel_Item(
                                                        jArray.getJSONObject(i).getString("id"),
                                                        jArray.getJSONObject(i).getString("order_no").trim(),
                                                        str_order_date,
                                                        jArray.getJSONObject(i).getString("supplier_id").trim(),
                                                        "",
                                                        jArray.getJSONObject(i).getString("parts_no").trim(),
                                                        jArray.getJSONObject(i).getString("parts_name").trim(),
                                                        jArray.getJSONObject(i).getString("rank").trim(),
                                                        "",
                                                        jArray.getJSONObject(i).getString("qty").trim(),
                                                        jArray.getJSONObject(i).getString("action_act_qty"),
                                                        jArray.getJSONObject(i).getString("status").trim(),
                                                        jArray.getJSONObject(i).getString("unit_qty"),
                                                          ""));
                                    }
                                }
                                update_map_sch();
                                Log.d(getString(R.string.tag), String.valueOf(list_item.size()));
                            }catch (JSONException e) {
                                new SweetAlertDialog(LabelSchedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR")
                                        .setContentText(e.getMessage())
                                        .show();
                            }
                        }
                    }.execute();

                }catch (JSONException e) {
                    new SweetAlertDialog(LabelSchedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("ERROR")
                            .setContentText(e.getMessage())
                            .show();
                }
            }
        }catch (ParseException e){
            new SweetAlertDialog(LabelSchedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR : check date from-to ")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void update_map_sch() {
        Log.d(getString(R.string.tag), String.valueOf(map_sch_item.size()));

        if (map_sch_item.size() > 0) {
            for (String key : map_sch_item.keySet()) {
                ScheduleLabel_Item item = map_sch_item.get(key);
                String supplier_code = item.getSupplier_id();
                String item_id = item.getPart_no();
                String supplier_name = "", qty_per_box = "";

                //supplier_name
                if (Settings.getMap_supplier().containsKey(supplier_code)) {
                    Supplier_list sup = Settings.getMap_supplier().get(supplier_code);
                    supplier_name = sup.getName();
                } else {
                    supplier_name = "";
                }

                //qty per box
                if (Settings.getMap_packing().containsKey(item_id)) {
                    PackingStandard_list box = Settings.getMap_packing().get(item_id);
                    qty_per_box = box.getQty();
                } else {
                    qty_per_box = "";
                }

                item.setSupplier_name(supplier_name);
                item.setQty_per_box(qty_per_box);
                map_sch_item.put(key, item);
            }
        }

        set_view_data();
    }

    private void set_view_data() {
        list_item.clear();
        String search_part = txt_part_no.getText().toString().trim();
        if (search_part.trim().equals("All")){
            search_part = "";
        }

        for (String key : map_sch_item.keySet()) {
            ScheduleLabel_Item item = map_sch_item.get(key);
            String part_no = item.getPart_no();
            Log.d(getString(R.string.tag), part_no.substring(4, 11).trim() + "/" + search_part);

            if (search_part.trim().equals("")){
                list_item.add(new ScheduleLabel_Item(
                        item.getSchedule_id(),
                        item.getOrder_no(),
                        item.getOrder_date(),
                        item.getSupplier_id(),
                        item.getSupplier_name(),
                        item.getPart_no(),
                        item.getPart_name(),
                        item.getRank(),
                        item.getLocation(),
                        item.getPlan_qty(),
                        item.getAct_qty(),
                        item.getStatus(),
                        item.getUnit(),
                        item.getQty_per_box()));
            }else {
                if (part_no.substring(4, 11).trim().equals(search_part)) {
                    list_item.add(new ScheduleLabel_Item(
                            item.getSchedule_id(),
                            item.getOrder_no(),
                            item.getOrder_date(),
                            item.getSupplier_id(),
                            item.getSupplier_name(),
                            item.getPart_no(),
                            item.getPart_name(),
                            item.getRank(),
                            item.getLocation(),
                            item.getPlan_qty(),
                            item.getAct_qty(),
                            item.getStatus(),
                            item.getUnit(),
                            item.getQty_per_box()));
                }
            }
        }
        Log.d(getString(R.string.tag), "no Check" + String.valueOf(list_item.size()));

        adapter_label = new ScheduleLabel_Adapter(list_item, this);
        view_schedule.setAdapter(adapter_label);
        Log.d(getString(R.string.tag), "set adapter");

    }


    @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;
            }
        }

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