package com.tomas.lps_asi;

import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.lps_asi.ListData.User_Lists;
import com.tomas.lps_asi.lib.KeyMapping;
import com.tomas.lps_asi.lib.Settings;
import com.tomas.lps_asi.lib.common.AsyncHttpClient;
import com.tomas.lps_asi.lib.common.Scanner;
import com.tomas.lps_asi.lib.common.Utils;

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

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class Cleaning_Activity extends Scanner implements View.OnClickListener {
    TextView txt_date, txt_machine, txt_user_id;
    ImageButton imb_back;
    Button btn_clean;
    Calendar calendar, end_calendar, start_calendar;;
    SimpleDateFormat date, date_time_fm, date_fm;
    String str_today, end_dt, start_dt;

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

        calendar = Calendar.getInstance();
        date = new SimpleDateFormat("yyyy-MM-dd");
        date_time_fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        date_fm = new SimpleDateFormat("yyyy-MM-dd");
        str_today = date.format(calendar.getTime());
        txt_date = (TextView) findViewById(R.id.txt_date);
        txt_date.setText(str_today);

        txt_machine = (TextView) findViewById(R.id.txt_machine_code);
        txt_user_id = (TextView) findViewById(R.id.txt_user_id);

        imb_back = (ImageButton) findViewById(R.id.imb_back);
        btn_clean = (Button) findViewById(R.id.btn_clean);

    }

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

            case R.id.btn_clean:
                if (txt_machine.getText().toString().trim().equals("")
                        || txt_user_id.getText().toString().trim().equals("")){

                    new SweetAlertDialog(Cleaning_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("กรุณาสแกนข้อมูลให้ครบ!")
                            .show();
                }else {
                    Block_button();
                    Save_Cleaning();
                }
                break;

        }
    }

    private void Block_button() {
        btn_clean.setEnabled(false);
        btn_clean.setBackgroundResource(R.drawable.button_backgroup_gray);
    }

    private void Unblock_button() {
        btn_clean.setEnabled(true);
        btn_clean.setBackgroundResource(R.drawable.button_backgroup_green);
    }



    @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 (data.length() == 6) {//scan user
                if (Settings.getMap_user().containsKey(data)){
                    String user_id = data;
                    txt_user_id.setText(user_id);

                    User_Lists lists = Settings.getMap_user().get(data);
                    String nameEng = lists.getNameEng();
                    Log.d(getString(R.string.tag), "nameEng : " + nameEng);

                }else {
                    txt_user_id.setText("");
                    new SweetAlertDialog(Cleaning_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("ไม่พบรหัสพนักงาน!")
                            .show();
                }
            } else if (data.substring(0,2).trim().equals("TP") ) {//scan machine
                if(Settings.getMachineList().containsKey(data)){
                    txt_machine.setText(data);
                }else {
                    txt_machine.setText("");
                    new SweetAlertDialog(Cleaning_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("ไม่พบเครื่องจักร!")
                            .show();
                }
            }else {
                new SweetAlertDialog(Cleaning_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("QR Code ไม่ถูกต้อง!")
                        .show();
            }
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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


    private void Save_Cleaning() {
        //get start_dt end_dt
        start_calendar = Calendar.getInstance();
        end_calendar = Calendar.getInstance();
        //date gen lot
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        String dt_to_server = date_time_fm.format(calendar.getTime());

//ทำไว้เผื่อเช็คว่าวันนี้ทำรึยัง แต่ถ้าจะเช็คตามกะยากนะ ต้องเขียนใหม่
//        try {//check date time before 8:00AM
//            Date today = new Date();
//            SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
//            String current_time = sdf.format(today);
//            Date start = sdf.parse("08:00 AM");
//            Date current = sdf.parse(current_time);
//
//            if (current.before(start)) {
//                Log.d("get_start_dt", "before" );
//
//                start_calendar.add(Calendar.DATE, -1);
//                start_dt = date_fm.format(start_calendar.getTime());
//
//                calendar.add(Calendar.DATE, -1);
//                end_dt = date_fm.format(end_calendar.getTime());
//
//            }else{
//                Log.d("get_start_dt", "after" );
//                end_calendar.add(Calendar.DATE, +1);
//                end_dt = date_fm.format(end_calendar.getTime());
//                start_dt = date_fm.format(start_calendar.getTime());
//
//            }
//        } catch (ParseException e) {
//            // Invalid date was entered
//            Unblock_button();
//            new SweetAlertDialog(Cleaning_Activity.this, SweetAlertDialog.ERROR_TYPE)
//                    .setTitleText("ERROR get_date")
//                    .setContentText(e.getMessage())
//                    .show();
//        }
//        start_dt = start_dt + " 08:00:00";
//        end_dt = end_dt + " 07:59:59";
//
//        Log.d(getString(R.string.tag), "start_dt: " + start_dt);
//        Log.d(getString(R.string.tag), "end_dt: " + end_dt);

        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "add");
            JSONArray jsonArray = new JSONArray();
            Map<String, String> jsParams = new HashMap<>();
            jsParams.put("machine_code",txt_machine.getText().toString().trim());
            jsParams.put("create_dt", dt_to_server);
            jsParams.put("create_user_id", txt_user_id.getText().toString().trim());
//            jsParams.put("start_dt", start_dt);
//            jsParams.put("end_dt", end_dt);
            JSONObject jsonObject = new JSONObject(jsParams);
            jsonArray.put(jsonObject);
            json.put("cleaning_datas", jsonArray);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/cleaning_heater_box.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        Log.d(getString(R.string.tag), "response" + response);
                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");

                        if (status.trim().equals("success") && affected_rows > 0) {
                            //SUCCESS
                            new SweetAlertDialog(Cleaning_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                                    .setTitleText("สำเร็จ")
                                    .setContentText("บันทึกการทำความสะอาดสำเร็จ")
                                    .show();
                            Unblock_button();
                            Clear_layout();
                        } else {
                            String error = jsonObject.getString("error");
                            error = URLDecoder.decode(error);
                            new SweetAlertDialog(Cleaning_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();
                            Unblock_button();
                            Clear_layout();
                        }
                    } catch (JSONException e) {
                        new SweetAlertDialog(Cleaning_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("Error")
                                .setContentText(e.getMessage())
                                .show();
                        Unblock_button();
                    }
                }
            }.execute();
        } catch (Exception e) {
            new SweetAlertDialog(Cleaning_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("Error")
                    .setContentText(e.getMessage())
                    .show();
            Unblock_button();
        }
    }

    private void Clear_layout() {
        txt_user_id.setText("");
        txt_machine.setText("");
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode >= KeyMapping.P1.getId()
                && keyCode <= KeyMapping.P4.getId())
        {
            switch (KeyMapping.fromId(keyCode)) {
                case P1:
                    imb_back.performClick();
                    break;

                case P2:
                    btn_clean.performClick();
                    break;

            }
        }

        return super.onKeyUp(keyCode, event);
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}