package com.tomas.pcs_asi;

import androidx.constraintlayout.widget.ConstraintLayout;
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.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.pcs_asi.Adapter.Schedule_DB_Adapter;
import com.tomas.pcs_asi.ListData.Get_Schedule_DB;
import com.tomas.pcs_asi.lib.KeyMapping;
import com.tomas.pcs_asi.lib.Settings;
import com.tomas.pcs_asi.lib.common.AsyncHttpClient;
import com.tomas.pcs_asi.lib.common.Scanner;
import com.tomas.pcs_asi.lib.common.Utils;

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

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

import cn.pedant.SweetAlert.SweetAlertDialog;

public class DB_Schedule_Activity extends Scanner implements View.OnClickListener {
    Calendar calendar;
    SimpleDateFormat date;
    TextView txt_message;
    EditText edt_date;
    RecyclerView recyclerView;
    String str_date;
    List<Get_Schedule_DB> list_item;
    Schedule_DB_Adapter schedule_adapter;
    ConstraintLayout layout_alert;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_die_bond_schedule);
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);
        edt_date = (EditText) findViewById(R.id.edt_date);
        calendar = Calendar.getInstance();
        date = new SimpleDateFormat("dd/MM/yyyy");
        str_date = date.format(calendar.getTime());

        list_item = new ArrayList<Get_Schedule_DB>();

        layout_alert = (ConstraintLayout)findViewById(R.id.layout_alert);
        txt_message = (TextView)findViewById(R.id.txt_message);
        txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");

        edt_date.setText(str_date);
        edt_date.setInputType(InputType.TYPE_NULL);
        edt_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final Calendar currentDate = Calendar.getInstance();
                new DatePickerDialog(DB_Schedule_Activity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        str_date = (String.format("%2s",dayOfMonth).replace(' ','0'))+"/"+
                                (String.format("%2s",monthOfYear + 1).replace(' ','0')+"/"+ year);
                        edt_date.setText(str_date);

                        Get_Schedule(str_date);

                    }
                }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).show();
            }
        });
        recyclerView = (RecyclerView)findViewById(R.id.view_sch_db);
        recyclerView.setHasFixedSize(true);
        recyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    protected void onStart() {
        super.onStart();
        edt_date.setText(str_date);
        Get_Schedule(str_date);
    }

    private void Get_Schedule(String date) {
        list_item.clear();
        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");

            JSONObject json = new JSONObject();
            json.put("cmd", "get_schedule_db");
            json.put("date", date);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api")+ "/production_plan.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){
                            View_data();
                            layout_alert.setVisibility(View.GONE);
                            Toast.makeText(getApplicationContext(), "ไม่พบแผนงาน วันที่:"+date+" ", Toast.LENGTH_LONG).show();
//                            new SweetAlertDialog(DB_Schedule_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                                    .setTitleText("WARNING")
//                                    .setContentText("Plan not found!")
//                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++){
                                list_item.add(new Get_Schedule_DB(
                                        jArray.getJSONObject(i).getString("ICSProductCode").trim(),
                                        jArray.getJSONObject(i).getString("job_order").trim(),
                                        jArray.getJSONObject(i).getString("qty_lot").trim(),
                                        jArray.getJSONObject(i).getString("FINISHED").trim(),
                                        jArray.getJSONObject(i).getString("WORKING").trim()));
                            }
                            View_data();
                            layout_alert.setVisibility(View.GONE);
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(DB_Schedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(DB_Schedule_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

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

        schedule_adapter = new Schedule_DB_Adapter(list_item, DB_Schedule_Activity.this);
        recyclerView.setAdapter(schedule_adapter);
        Log.d(getString(R.string.tag), "set adapter");
    }

    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
        if (data.trim().equals(""))
            return;

        try {
            if (!data.trim().equals("")) {
                Settings.setICS(data.trim());
                Settings.setJobOrder("");
                Settings.setItemType("");
                Settings.setDbProcessTimes(0);

                // Discard the ScanManager class instance.
                mScanManager.removeDataListener(DB_Schedule_Activity.this);
                // Discard the ScanManager class instance to release the resources.
                mScanManager.releaseScanManager();

                Intent intent = new Intent(DB_Schedule_Activity.this, DB_Lot_Activity.class);
                startActivity(intent);
                finish();
            }

            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 void onClick(View view) {
        switch (view.getId()) {
            case R.id.imb_back:
                finish();
                break;
        }
    }

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