package com.tomas.pcs_asi;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.pcs_asi.Adapter.Oven_Adapter;
import com.tomas.pcs_asi.Adapter.Tools_Adapter;
import com.tomas.pcs_asi.ListData.Get_Item_Tools;
import com.tomas.pcs_asi.ListData.Get_Machine;
import com.tomas.pcs_asi.ListData.Item_Oven;
import com.tomas.pcs_asi.ListData.User_Lists;
import com.tomas.pcs_asi.lib.ConvertStringToCalendar;
import com.tomas.pcs_asi.lib.KeyMapping;
import com.tomas.pcs_asi.lib.ProductionSchedule;
import com.tomas.pcs_asi.lib.Settings;
import com.tomas.pcs_asi.lib.common.AsyncHttpClient;
import com.tomas.pcs_asi.lib.common.AsyncHttpClientMultipart;
import com.tomas.pcs_asi.lib.common.MyAlertDialog;
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.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class Dicer_Activity extends Scanner implements View.OnClickListener {
    TextView txt_ics, txt_job_order, txt_lot_no, txt_tool, txt_user, txt_machine, txt_overdue_title, txt_overdue_dt, txt_message, txt_leader;
    String str_process, str_ics, str_job_order, str_lot_no, str_mc_type, str_dicer_id, str_status,SCH_ID, ICS_CODE, JOB_ORDER, LOT_NO,
            PROCESS, STATUS, DICER_PLAN_START,dt_format = "yyyy-MM-dd HH:mm:ss",dt_to_photo, dt_to_server, str_machine, str_user_id,
            DICER_ID, status_tool, str_frequency, end_dt, start_dt, str_shift, str_item_type;

    EditText edt_sp1, edt_sp2;
    RecyclerView view_process_sheet, view_tool;
    LinearLayout layout_dicer, layout_btn_working, layout_btn_edit, layout_input, layout_btn_start, layout_tool, layout_line_sp;
    ConstraintLayout layout_alert_plan,layout_alert, layout_nurse_call;
    private static final int REQUEST_IMAGE_CAPTURE = 200;
    public static final int SIGN_INVOICE_ACTIVITY = 100;
    public static final int SIGN_DO_ACTIVITY = 101;
    Calendar calendar, end_calendar, start_calendar;;
    SimpleDateFormat fm_dt_server, fm_dt_photo, fm_datetime;

    Map<String, Item_Oven>map_item_dicer;
    Map<String, Get_Item_Tools> map_tools;
    Map<String, Get_Item_Tools> map_tools_scan;
    List<Get_Item_Tools>list_tools;
    List<Get_Item_Tools>list_tool_his;
    List<Item_Oven> list_dicer;
    int scan = 0, Max_line_SP;
    boolean Overdue, mode_edit, status_working, b_confirm, nurse_call;
    Oven_Adapter oven_adapter;
    Tools_Adapter tools_adapter;
    Button btn_start;
    Map<String, Get_Machine> map_machine;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dicer);
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);
        fm_dt_server = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        fm_dt_photo = new SimpleDateFormat("yyyyMMdd_HHmmss");
        fm_datetime = new SimpleDateFormat("yyyy-MM-dd");

        nurse_call = false;
        mode_edit = false;
        Overdue = false;
        status_working = false;
        b_confirm = true;
        status_tool = ProductionSchedule.STATUS_TM.NORMAL.toString();

        map_item_dicer = new LinkedHashMap<>();
        list_dicer = new ArrayList<Item_Oven>();
        map_tools_scan = new LinkedHashMap<>();
        list_tools = new ArrayList<Get_Item_Tools>();
        list_tool_his = new ArrayList<Get_Item_Tools>();
        map_tools = new LinkedHashMap<>();
        map_machine = new LinkedHashMap<>();

        layout_nurse_call = (ConstraintLayout) findViewById(R.id.layout_nurse_call);
        txt_leader = (TextView)findViewById(R.id.txt_leader);

        layout_dicer = (LinearLayout) findViewById(R.id.layout_dicer);
        layout_alert_plan = (ConstraintLayout)findViewById(R.id.layout_alert_plan);
        layout_alert = (ConstraintLayout)findViewById(R.id.layout_alert);
        layout_btn_working = (LinearLayout)findViewById(R.id.layout_btn_working);
        layout_btn_edit = (LinearLayout)findViewById(R.id.layout_btn_edit);
        layout_input = (LinearLayout)findViewById(R.id.layout_input);
        layout_btn_start = (LinearLayout)findViewById(R.id.layout_btn_start);
        layout_tool = (LinearLayout)findViewById(R.id.layout_tool);
        layout_line_sp = (LinearLayout)findViewById(R.id.layout_line_sp);

        btn_start = (Button)findViewById(R.id.btn_start);
        txt_user = (TextView)findViewById(R.id.txt_user);
        txt_ics = (TextView)findViewById(R.id.txt_ics);
        txt_job_order = (TextView)findViewById(R.id.txt_job_order);
        txt_lot_no = (TextView)findViewById(R.id.txt_lot_no);
        txt_machine = (TextView)findViewById(R.id.txt_machine);
        txt_overdue_title = (TextView)findViewById(R.id.txt_overdue_title);
        txt_overdue_dt= (TextView)findViewById(R.id.txt_overdue_dt);
        txt_message = (TextView)findViewById(R.id.txt_message);
        txt_tool= (TextView)findViewById(R.id.txt_tool);

        edt_sp1 = (EditText)findViewById(R.id.edt_sp1);
        edt_sp1.requestFocus();
        edt_sp1.setShowSoftInputOnFocus(false);
        edt_sp2 = (EditText)findViewById(R.id.edt_sp2);
        edt_sp2.requestFocus();
        edt_sp2.setShowSoftInputOnFocus(false);

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

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

        str_process = Settings.getPROCESS();
        str_ics = Settings.getICS();
        str_job_order  = Settings.getJobOrder();
        str_lot_no = Settings.getLotNo();
        str_mc_type = Settings.getMcType();
        str_status = Settings.getSTATUS();
        str_item_type = Settings.getItemType();

        Log.d(getString(R.string.tag), "Oven Activity : " + str_process+" | "+ str_status+"|"+str_mc_type+"|"+str_item_type);

        txt_ics.setText(str_ics);
        txt_job_order.setText(str_job_order);
        txt_lot_no.setText(str_lot_no);

        if (str_status.trim().equals(ProductionSchedule.STATUS.MOLD_FINISHED.toString())){
            Check_ProcessSheet();

        }else { //status == dicer working
            status_working = true;
            str_user_id = Settings.getUserId();
            str_machine = Settings.getMACHINE();
            str_dicer_id = Settings.getDicerId();

            txt_user.setText(str_user_id);
            txt_machine.setText(str_machine);
            txt_user.setBackgroundResource(R.drawable.img_backgroup);
            txt_machine.setBackgroundResource(R.drawable.img_backgroup);

            layout_input.setVisibility(View.GONE);
            layout_btn_start.setVisibility(View.GONE);
            layout_btn_working.setVisibility(View.VISIBLE);

            Log.d(getString(R.string.tag), "Dicer ID : " + str_dicer_id);

            Search_ProcessSheet_DICER(str_dicer_id);
            Get_tool_his();
        }

        Get_Tool(str_ics);
        Get_Machine(str_mc_type, str_item_type);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_ok:
                Overdue = false;
                layout_alert_plan.setVisibility(View.GONE);
                layout_dicer.setVisibility(View.VISIBLE);
                break;

            case R.id.imb_back:
                    Intent intent = new Intent(Dicer_Activity.this, Search_ProcessSheet_Lot_Activity.class);
                    startActivity(intent);
                    finish();
                break;

            case R.id.ibtn_camera:
                dispatchTakePictureIntent();
                break;

            case R.id.btn_start:
                if (b_confirm == true) {
                    Block_button();
                    Check_completed_data();
                }
                break;

            case R.id.btn_edit:
                Mode_Edit();
                break;

            case R.id.btn_output:
                Intent i = new Intent(Dicer_Activity.this, Dicer_Output_Activity.class);
                startActivity(i);
                finish();
                break;

            case R.id.btn_save_edit:
                if (map_tools_scan.size() > 0){
                    if (b_confirm == true) {
                        Block_button();
                        Save_Tools(str_dicer_id);
                    }
                }else{
                    new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("กรุณาสแกน tool!")
                            .show();
                }
                break;

            case R.id.btn_ok_nurse_call:
                OK_NurseCall();
                break;

            case R.id.btn_cancel_nurse_call:
                Cancel_NurseCall();
                break;
        }
    }

    private void OK_NurseCall() {
        nurse_call = false;
        layout_dicer.setVisibility(View.VISIBLE);
        layout_nurse_call.setVisibility(View.GONE);

        if (txt_leader.getText().toString().trim().equals("")){
            Unblock_button();
            new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกนรหัส leader!")
                    .show();
        }else {
            Update_Dicer();
        }
    }

    private void Cancel_NurseCall() {
        nurse_call = false;
        Unblock_button();
        layout_dicer.setVisibility(View.VISIBLE);
        layout_nurse_call.setVisibility(View.GONE);
        txt_leader.setText("");
    }
    private void Block_button() {
        b_confirm = false;
        btn_start.setEnabled(false);
        btn_start.setBackgroundResource(R.drawable.button_backgroup_gray);
    }

    private void Unblock_button() {
        b_confirm = true;
        btn_start.setEnabled(true);
        btn_start.setBackgroundResource(R.drawable.button_backgroup_green);
    }
    private void Mode_Edit() {
        status_tool = ProductionSchedule.STATUS_TM.CHANGE.toString();
        status_working = false;
        mode_edit = true;
        layout_btn_working.setVisibility(View.GONE);
        layout_btn_edit.setVisibility(View.VISIBLE);

        list_tool_his.clear();
        Set_View_Tools_His();
    }

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

        try {
            Log.d(getString(R.string.tag), "scan data : " + data);
            if (status_working == true)
                return;

            if (scan == 0) {
               if (map_machine.containsKey(data.trim())) {//machine

                   if (mode_edit == true){
                       new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.WARNING_TYPE)
                               .setTitleText("แจ้งเตือน")
                               .setContentText("ไม่สามารถเปลี่ยนเครื่องจักรได้!")
                               .show();
                   }else{
                       Get_Machine machine = map_machine.get(data.trim());
                       String line = machine.getMax_line_sp();
                       str_frequency = machine.getFrequency();

                       Max_line_SP = Integer.parseInt(line.trim()==""?"0":line);
                       txt_machine.setText(data.trim());
                       layout_line_sp.setVisibility(View.VISIBLE);

                       Log.d(getString(R.string.tag), "machine: " + data+"|"+str_frequency+"|"+Max_line_SP);
                   }

                } else if (data.trim().length() == 10) {//ics_code
                   if (mode_edit == true)
                       return;

                   if (map_item_dicer.size() == 0){
                       scan = 1;
                       txt_ics.setText(data.trim());
                       txt_job_order.setText("");
                       txt_lot_no.setText("");

                   }else {
                       if (ICS_CODE.trim().equals(data.trim())) {
                           scan = 1;
                           txt_ics.setText(data.trim());
                           txt_job_order.setText("");
                           txt_lot_no.setText("");

                       } else {
                           new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                   .setTitleText("แจ้งเตือน")
                                   .setContentText("ICS Product Code ไม่ตรงกัน")
                                   .show();
                       }
                   }
                } else if (data.trim().substring(0, 2).trim().equals("TL")) {//tool
                   txt_tool.setText("");
                   //tool
                   if (map_tools.containsKey(data.trim())) {
                       if (map_tools_scan.containsKey(data.trim())) {//tool duplicate --> del
                           map_tools_scan.remove(data.trim());

                       } else {
                           txt_tool.setText(data.trim());
                           Get_Item_Tools get_item_tools = map_tools.get(data.trim());
                           map_tools_scan.put(data.trim(), new Get_Item_Tools(
                                   get_item_tools.getICSProductCode(),
                                   get_item_tools.getProduction(),
                                   get_item_tools.getTool(),
                                   get_item_tools.getToolName(),
                                   get_item_tools.getToolCode(),
                                   status_tool));

                       }
                       Set_View_Tools_Scan();
                   }else{
                       txt_tool.setText("");
                       new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.WARNING_TYPE)
                               .setTitleText("แจ้งเตือน")
                               .setContentText("ไม่พบ Tool!")
                               .show();
                   }
               } else if (data.trim().length() == 6) {//user
                   Check_User(data.trim());

               } else {
                   new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.WARNING_TYPE)
                           .setTitleText("แจ้งเตือน")
                           .setContentText("QR code ไม่ถูกต้อง!")
                           .show();
                }

            } else if (scan == 1) {
                if (mode_edit == true)
                    return;
                scan = 2;
                txt_job_order.setText(data.trim());

            } else {
                if (mode_edit == true)
                    return;
                scan = 0;
                txt_lot_no.setText(data.trim());
                Check_ProcessSheet();
            }
                Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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

    private void Check_User(String data) {
        if (Settings.getMap_user().containsKey(data)){

            if ( nurse_call == true){//scan leader
                User_Lists lists = Settings.getMap_user().get(data);
                String str_role = lists.getRole();
                if (str_role.trim().equals("LEADER")){

                    txt_leader.setText(data);

                }else {
                    new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("รหัสพนักงานนี้ไม่ใช่ leader!!")
                            .show();
                }
            }else {
                if (Settings.getMap_user().get(data).getDicer().trim().equals("1")){
                    txt_user.setText(data);

                }else {
                    txt_user.setText("");
                    new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("ไม่อนุญาตให้ทำงานใน Dicer")
                            .show();
                }
            }
        }else {
            txt_user.setText("");
            new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("ไม่พบรหัสพนักงาน!")//OK
                    .show();
        }
    }

    private void Search_ProcessSheet_DICER(String dicer_id) {
        list_dicer.clear();
        map_item_dicer.clear();

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

            JSONObject json = new JSONObject();
            json.put("cmd", "search_dicer");
            json.put("dicer_id", dicer_id);

            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){
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Dicer ID : "+dicer_id+" not found!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                map_item_dicer.put(String.valueOf(i), new Item_Oven(
                                        jArray.getJSONObject(i).getString("sch_id").trim(),
                                        jArray.getJSONObject(i).getString("ICSProductCode").trim(),
                                        jArray.getJSONObject(i).getString("job_order").trim(),
                                        jArray.getJSONObject(i).getString("lot_no").trim(),
                                        ""));
                                Log.d(getString(R.string.tag), "map_item_dicer: " + String.valueOf(map_item_dicer.size()));
                            }
                            Set_view_dicer();
                            layout_alert.setVisibility(View.GONE);
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

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

            JSONObject json = new JSONObject();
            json.put("cmd", "search_tools_dicer");
            json.put("dicer_id", str_dicer_id);
            json.put("process", str_process);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/tool_factor_list.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){
                            list_tool_his.clear();
                            layout_alert.setVisibility(View.GONE);
                        }else {
                            for(int i=0; i<jArray.length(); i++) {
                                list_tool_his.add(new Get_Item_Tools(
                                        "",
                                        "",
                                        "",
                                        jArray.getJSONObject(i).getString("tool_name").trim(),
                                        jArray.getJSONObject(i).getString("tool_code").trim(),
                                        jArray.getJSONObject(i).getString("status").trim()));
                            }
                            layout_alert.setVisibility(View.GONE);
                        }
                        Log.d(getString(R.string.tag), String.valueOf(list_tool_his.size()));
                        Set_View_Tools_His();
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Set_View_Tools_His() {
        tools_adapter = new Tools_Adapter(list_tool_his, Dicer_Activity.this);
        view_tool.setAdapter(tools_adapter);

    }

    private void Check_completed_data() {
        if (txt_machine.getText().toString().trim().equals("")
                || edt_sp1.getText().toString().trim().equals("")
                || txt_user.getText().toString().trim().equals("")
                || map_tools_scan.size() == 0) {

            Unblock_button();
            new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณากรอกข้อมูลให้ครบ!")
                    .show();
        }else {
            //check line sp
            int sp1, sp2;
            sp1 = Integer.parseInt(edt_sp1.getText().toString());
            sp2 = Integer.parseInt(edt_sp2.getText().toString().equals("") ? "0" : edt_sp2.getText().toString().trim());
            Log.d(getString(R.string.tag), "Line sp : " + sp1+" | "+sp2+" | "+Max_line_SP);

            if (sp1 <= Max_line_SP){//check sp1
                if (sp2 > 0){//have sp1 & sp2
                    if (sp2 <= Max_line_SP){//check sp2
                        Update_Dicer();

                    }else {
                        nurse_call = true;
                        layout_dicer.setVisibility(View.GONE);
                        layout_nurse_call.setVisibility(View.VISIBLE);
                    }
                }else {
                    Update_Dicer(); //have sp1 only
                }
            }else {
                nurse_call = true;
                layout_dicer.setVisibility(View.GONE);
                layout_nurse_call.setVisibility(View.VISIBLE);
            }
        }
    }


    private void Update_Dicer() {
            Block_button();

            calendar = Calendar.getInstance();
            calendar = (Calendar) calendar.clone();
            dt_to_server = fm_dt_server.format(calendar.getTime());
            dt_to_photo = fm_dt_photo.format(calendar.getTime());
            Log.d(getString(R.string.tag), "dt_to_server : " + dt_to_server+"/"+dt_to_photo);

            DICER_ID = txt_machine.getText().toString().trim()+dt_to_photo;
            Log.d(getString(R.string.tag), "DICER_ID: " + DICER_ID);

            try {
                layout_alert.setVisibility(View.VISIBLE);
                txt_message.setText("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

                JSONObject json = new JSONObject();
                json.put("cmd", "update_dicer_working");
                JSONArray jsonArray = new JSONArray();

                for (String key : map_item_dicer.keySet()) {
                    Item_Oven item = map_item_dicer.get(key);

                    Map<String, String> jsonParams = new HashMap<>();
                    jsonParams.put("sch_id", item.getSch_id());
                    jsonParams.put("dicer_id", DICER_ID);
                    jsonParams.put("machine", txt_machine.getText().toString().trim());
                    jsonParams.put("dicer_line_sp1", edt_sp1.getText().toString().trim());
                    jsonParams.put("dicer_line_sp2", edt_sp2.getText().toString().trim());
                    jsonParams.put("dicer_nurse_call_user_id",txt_leader.getText().toString().trim());
                    jsonParams.put("user_id", txt_user.getText().toString().trim());
                    jsonParams.put("act_dt", dt_to_server);

                    JSONObject jsonObject = new JSONObject(jsonParams);
                    jsonArray.put(jsonObject);
                }
                json.put("dicer_datas",jsonArray);
                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 {
                            JSONObject jsonObject = new JSONObject(response);
                            String status = jsonObject.getString("status");
                            int affected_rows = jsonObject.getInt("affected_rows");
                            if (status.equals("success") && affected_rows > 0) {
                                Save_Tools(DICER_ID);
                                layout_alert.setVisibility(View.GONE);
                            } else {
                                layout_alert.setVisibility(View.GONE);
                                Unblock_button();
                                new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR")
                                        .setContentText("Can't update ProductionPlan")
                                        .show();
                            }
                        } catch (JSONException e) {
                            Unblock_button();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(e.getMessage())
                                    .show();
                        }
                    }
                }.execute();
            } catch (Exception e) {
                layout_alert.setVisibility(View.GONE);
                Unblock_button();
                new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
    }

    private void Save_Tools(String dicer_id) {
        Block_button();
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        dt_to_server = fm_dt_server.format(calendar.getTime());
        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

            JSONObject json = new JSONObject();
            json.put("cmd", "add");
            JSONArray jsonArray = new JSONArray();

                for (String key : map_tools_scan.keySet()) {
                    Get_Item_Tools item = map_tools_scan.get(key);

                    for (String key_dicer : map_item_dicer.keySet()) {
                        Item_Oven item_dicer = map_item_dicer.get(key_dicer);

                        String str_sch_id = item_dicer.getSch_id();
                        Map<String, String> jsonParams = new HashMap<>();
                        jsonParams.put("sch_id", str_sch_id);
                        jsonParams.put("tool_code", item.getToolCode());
                        jsonParams.put("tool_name", item.getToolName());
                        jsonParams.put("process", str_process);
                        jsonParams.put("check_times", "1");
                        jsonParams.put("dicer_id", dicer_id);
                        jsonParams.put("status", item.getStatus());
                        jsonParams.put("create_dt", dt_to_server);
                        jsonParams.put("create_user_id", txt_user.getText().toString().trim());
                        JSONObject jsonObj = new JSONObject(jsonParams);
                        jsonArray.put(jsonObj);
                    }
                }
            json.put("t_datas",jsonArray);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/tool_factor_list.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");
                        int affected_rows = jsonObject.getInt("affected_rows");
                        if (status.equals("success") && affected_rows > 0) {
                            if (mode_edit == true) {// mold : edit.
                                Insert_RandomCheck_Edit();
                            }else {
                                RandomCheck_Status();
                            }
                        }else {
                            Unblock_button();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Can't insert ToolFactorList")
                                    .show();
                        }
                    }catch (JSONException e) {
                        Unblock_button();
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (Exception e) {
            Unblock_button();
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Insert_RandomCheck_Edit() {
        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังตรวจสอบการสุ่มตรวจ...");

            JSONObject json = new JSONObject();
            json.put("cmd", "random_check_edit");
            json.put("sch_id",str_dicer_id);
            json.put("process", str_process);
            json.put("machine_code", txt_machine.getText().toString().trim());

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

                    try {
                        layout_alert.setVisibility(View.GONE);

                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status").trim();
                        String message = jsonObject.getString("message").trim();

                        if (status.trim().equals("error")){
                            Unblock_button();
                            new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(message)
                                    .show();
                        }else {//success

                            SweetAlertDialog pDialog = new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.WARNING_TYPE);
                            pDialog.setTitleText("แจ้งเตือนการสุ่มตรวจสอบ");
                            pDialog.setContentText(message);
                            pDialog.setCancelable(false);
                            pDialog.setConfirmText("รับทราบ");
                            pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismiss();
                                    finish();
                                }
                            });
                            pDialog.show();
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }

    }

    private void RandomCheck_Status() {
        //get start_dt end_dt
        //get start_dt end_dt
        start_calendar = Calendar.getInstance();
        end_calendar = Calendar.getInstance();
        //date gen lot
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        try {//check date time before 8:00AM
            Date today = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            String current_time = sdf.format(today);
            Date day_start = sdf.parse("07:59:59");
            Date day_end = sdf.parse("20:00:00");
            Date midnight = sdf.parse("23:59:59");
            Date current = sdf.parse(current_time);

            if (current.after(day_start) && current.before(day_end) ) {
                Log.d("get_start_dt", "shift_day" );
                str_shift = "Shift_Day";
                start_dt = fm_datetime.format(start_calendar.getTime());
                end_dt = fm_datetime.format(end_calendar.getTime());
                start_dt = start_dt + " 08:00:00";
                end_dt = end_dt + " 19:59:59";

            }else{
                Log.d("get_start_dt", "Shift_Night" );
                str_shift = "Shift_Night";

                if (current.after(midnight) && current.before(day_start) ){
                    start_calendar.add(Calendar.DATE, -1);
                    start_dt = fm_datetime.format(start_calendar.getTime());
                    start_dt = start_dt + " 20:00:00";

                    end_dt = fm_datetime.format(end_calendar.getTime());
                    end_dt = end_dt + " 07:59:59";
                    Log.d("after midnight", start_dt );
                    Log.d("after midnight", end_dt );
                }else {
                    start_dt = fm_datetime.format(start_calendar.getTime());
                    start_dt = start_dt + " 20:00:00";

                    end_calendar.add(Calendar.DATE, +1);
                    end_dt = fm_datetime.format(end_calendar.getTime());
                    end_dt = end_dt + " 07:59:59";
                    Log.d("before midnight", start_dt );
                    Log.d("before midnight", end_dt );
                }
            }
        } catch (ParseException e) {
            // Invalid date was entered
            Unblock_button();
            new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR get_date")
                    .setContentText(e.getMessage())
                    .show();
        }
        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังตรวจสอบการสุ่มตรวจ...");

            JSONObject json = new JSONObject();
            json.put("cmd", "random_check");
            json.put("sch_id", DICER_ID);
            json.put("model", ICS_CODE);
            json.put("process", str_process);
            json.put("machine_code", txt_machine.getText().toString().trim());
            json.put("frequency", str_frequency);
            json.put("shift", str_shift);
            json.put("start_dt", start_dt);
            json.put("end_dt", end_dt);

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

                    try {
                        layout_alert.setVisibility(View.GONE);

                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status").trim();
                        String message = jsonObject.getString("message").trim();

                        if (status.trim().equals("error")){
                            Unblock_button();
                            new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(message)
                                    .show();
                        }else {//success
                            if (message.trim().equals("Not checking")){
                                finish();
                            }else {
                                SweetAlertDialog pDialog = new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.WARNING_TYPE);
                                pDialog.setTitleText("แจ้งเตือนการสุ่มตรวจสอบ");
                                pDialog.setContentText(message);
                                pDialog.setCancelable(false);
                                pDialog.setConfirmText("รับทราบ");
                                pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        sweetAlertDialog.dismiss();
                                        finish();
                                    }
                                });
                                pDialog.show();
                            }
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }



    private void Set_View_Tools_Scan() {
        list_tools.clear();
        for (String key : map_tools_scan.keySet()){
            Get_Item_Tools tools = map_tools_scan.get(key);
            list_tools.add(new Get_Item_Tools(
                    tools.getICSProductCode(),
                    tools.getProduction(),
                    tools.getTool(),
                    tools.getToolName(),
                    tools.getToolCode(),
                    tools.getStatus()));
        }
        tools_adapter = new Tools_Adapter(list_tools, Dicer_Activity.this);
        view_tool.setAdapter(tools_adapter);
    }

    private void Check_ProcessSheet() {
        if (txt_ics.getText().toString().trim().equals("")
                ||txt_job_order.getText().toString().trim().equals("")
                ||txt_lot_no.getText().toString().trim().equals(""))
            return;

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

            JSONObject json = new JSONObject();
            json.put("cmd", "check_process_sheet");
            json.put("ics_product", txt_ics.getText().toString().trim());
            json.put("job_order", txt_job_order.getText().toString().trim());
            json.put("lot_no", txt_lot_no.getText().toString().trim());

            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){
                            Reset_view();
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ Process Sheet!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                PROCESS = jArray.getJSONObject(i).getString("process").trim();
                                STATUS = jArray.getJSONObject(i).getString("status").trim();
                                SCH_ID = jArray.getJSONObject(i).getString("sch_id").trim();
                                ICS_CODE = jArray.getJSONObject(i).getString("ICSProductCode").trim();
                                JOB_ORDER = jArray.getJSONObject(i).getString("job_order").trim();
                                LOT_NO = jArray.getJSONObject(i).getString("lot_no").trim();

                                JSONObject obj = jArray.getJSONObject(i);
                                JSONObject array_start_dt = obj.getJSONObject("dicer_plan_start_dt");
                                DICER_PLAN_START = array_start_dt.getString("date");
                                DICER_PLAN_START = DICER_PLAN_START.substring(0,19);
                                Log.d(getString(R.string.tag), "DICER_PLAN_START: " + DICER_PLAN_START);
                            }
                            Check_status();
                            layout_alert.setVisibility(View.GONE);
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Check_status() {
        if(map_item_dicer.containsKey(SCH_ID)){
            Log.d(getString(R.string.tag), "remove: " + SCH_ID);

            map_item_dicer.remove(SCH_ID);
            Set_view_dicer();
            Reset_view();

        }else {
            if (STATUS.trim().equals(ProductionSchedule.STATUS.MOLD_FINISHED.toString())) {
                    Check_Overdue(DICER_PLAN_START, "Start Plan DICER");

            } else {
                Reset_view();
                    new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("WARNING")
                            .setContentText("This Process sheet : "+STATUS)
                            .show();
            }
        }
    }

    private void Check_Overdue(String PLAN_DT, String Title) {
        calendar = ConvertStringToCalendar.convert(PLAN_DT, dt_format);
        String p_date1 = fm_dt_server.format(calendar.getTime());
        Log.d(getString(R.string.tag), "calendar: " + p_date1);

        calendar.add(Calendar.MINUTE, 30);
        String p_date2 = fm_dt_server.format(calendar.getTime());
        Log.d(getString(R.string.tag), "calendar: " + p_date2);

        Calendar now = Calendar.getInstance();
        Calendar now_dt = (Calendar) now.clone();
        String str_now = fm_dt_server.format(now_dt.getTime());
        Log.d(getString(R.string.tag), "now_dt: " + str_now);

        if (now_dt.after(calendar)){
            Log.d(getString(R.string.tag), "if alert");
            Overdue = true;
            txt_overdue_dt.setText(PLAN_DT);
            txt_overdue_title.setText(Title);
            layout_alert_plan.setVisibility(View.VISIBLE);
            layout_dicer.setVisibility(View.GONE);

        } else {
            Log.d(getString(R.string.tag), "else");
            Overdue = false;
            layout_alert_plan.setVisibility(View.GONE);
            layout_dicer.setVisibility(View.VISIBLE);

        }
        Log.d(getString(R.string.tag), "Add_mapItem: " + String.valueOf(map_item_dicer.size()));
        //add map
        map_item_dicer.put(SCH_ID, new Item_Oven(
                SCH_ID,
                ICS_CODE,
                JOB_ORDER,
                LOT_NO,
                "0"));
        Log.d(getString(R.string.tag), "else: " + String.valueOf(map_item_dicer.size()));
        Set_view_dicer();
    }

    private void Set_view_dicer() {
        //set view
        list_dicer.clear();
        for (String key : map_item_dicer.keySet()) {
            Item_Oven item = map_item_dicer.get(key);
            list_dicer.add(new Item_Oven(
                    item.getSch_id(),
                    item.getIcs_code(),
                    item.getJob_order(),
                    item.getLot_no(),
                    item.getMag_no()));
        }
        Log.d(getString(R.string.tag), "list_dicer: " + String.valueOf(list_dicer.size()));
        oven_adapter = new Oven_Adapter(list_dicer, Dicer_Activity.this,"DICER_START");
        view_process_sheet.setAdapter(oven_adapter);
        Reset_view();

    }


    private void Reset_view() {
        scan = 0;
        txt_job_order.setText("");
        txt_lot_no.setText("");

        if (map_item_dicer.size() == 0){
            txt_ics.setText("");
        }else {
            txt_ics.setHint(ICS_CODE);
        }
    }

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

            JSONObject json = new JSONObject();
            json.put("cmd", "get_machine");
            json.put("unit", unit);
            json.put("type", type);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/machine_master.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){
                            layout_alert.setVisibility(View.GONE);
                            SweetAlertDialog d = new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.WARNING_TYPE);
                            d.setCancelable(false);
                            d.setTitleText("แจ้งเตือน");
                            d.setContentText("ไม่พบเครื่องจักร : "+unit+"/"+type +"  \n กรุณาแจ้ง leader");
                            d.setConfirmText("รับทราบ");
                            d.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismiss();
                                    finish();
                                }
                            });
                            d.show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                map_machine.put(jArray.getJSONObject(i).getString("Code").trim(),
                                        new Get_Machine(
                                                jArray.getJSONObject(i).getString("Code").trim(),
                                                jArray.getJSONObject(i).getString("Type").trim(),
                                                jArray.getJSONObject(i).getString("Frequency").trim() == "null" ? "0" : jArray.getJSONObject(i).getString("Frequency").trim(),
                                                jArray.getJSONObject(i).getString("Max_line_SP").trim() == "null" ? "0" : jArray.getJSONObject(i).getString("Max_line_SP").trim(),
                                                jArray.getJSONObject(i).getString("Cavity").trim() == "null" ? "0" : jArray.getJSONObject(i).getString("Cavity").trim()));
                            }
                            layout_alert.setVisibility(View.GONE);
                        }
                        Log.d(getString(R.string.tag), String.valueOf(map_machine.size()));
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

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

            JSONObject json = new JSONObject();
            json.put("cmd", "search");
            json.put("ics_code", ics_code);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/tools.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){
                            layout_alert.setVisibility(View.GONE);
                            new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("ไม่พบ Tool!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                map_tools.put(jArray.getJSONObject(i).getString("ToolCode").trim(),
                                        new Get_Item_Tools(
                                                jArray.getJSONObject(i).getString("ICSProductCode").trim(),
                                                jArray.getJSONObject(i).getString("Production").trim(),
                                                jArray.getJSONObject(i).getString("Tool").trim(),
                                                jArray.getJSONObject(i).getString("ToolName").trim(),
                                                jArray.getJSONObject(i).getString("ToolCode").trim(),
                                                ""));
                            }
                            layout_alert.setVisibility(View.GONE);
                        }
                        Log.d(getString(R.string.tag), String.valueOf(map_tools.size()));
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Dicer_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        Boolean ItIsEmu = true;
        if (takePictureIntent.resolveActivity(getPackageManager()) != null
                || ItIsEmu) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
                ex.printStackTrace();
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.tomas.pcs_asi.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            } else {
                Toast.makeText(getApplicationContext(), "Photo file cannot be created!!", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(getApplicationContext(), "Camera activity not found!!", Toast.LENGTH_LONG).show();
        }
    }

    private Bitmap getPic() {

        // Get the dimensions of the bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;

        BitmapFactory.decodeFile(currentPhotoPath, bmOptions);

        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        //int scaleFactor = Math.max(1, Math.min(photoW/targetW, photoH/targetH));
        int scaleFactor = 1; // not scale

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;

        Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath, bmOptions);
        return bitmap;
    }

    String currentPhotoPath;
    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SIGN_INVOICE_ACTIVITY:
            case SIGN_DO_ACTIVITY:

                if (resultCode == Activity.RESULT_OK) {

                    finish();
                }
                break;
            case REQUEST_IMAGE_CAPTURE:
                if (resultCode == Activity.RESULT_OK) {
                    layout_alert.setVisibility(View.VISIBLE);
                    txt_message.setText("กรุณารอสักครู่ กำลังบันทึกรูปถ่าย...");

                    //Bitmap photo = (Bitmap) data.getExtras().get("data");
                    Bitmap photo = getPic();

                    // Save picture to server
                    calendar = Calendar.getInstance();
                    calendar = (Calendar) calendar.clone();
                    dt_to_photo = fm_dt_photo.format(calendar.getTime());
                    Log.d(getString(R.string.tag), "datetime_to_server: " + dt_to_photo);

                    try {
                        Map<String, Object> params = new HashMap<>();
                        String filename = str_process+"_"+dt_to_photo+".jpeg";;
                        Log.d(getString(R.string.tag), "filename: " + filename);

                        String url = Settings.getMgmtList().get("web_api") + "/save_image.php";
                        JSONObject json = new JSONObject();
                        json.put("image_file", filename);
                        params.put("json", json.toString());

                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                        byte[] bytes = Base64.getEncoder().encode(bos.toByteArray());
                        params.put(filename, bytes);

                        new AsyncHttpClientMultipart(getApplicationContext()
                                ,url
                                , params
                        ) {
                            @Override
                            public void onFinished(String response, int resp_code) {
                                Log.d(getString(R.string.tag), "response: " + response);
                                // update mapItems
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    Log.d(getString(R.string.tag), "response : " + jsonObject.getString("status"));
                                    if (jsonObject.getString("status").equals("success")) {
                                        Toast.makeText(getApplicationContext(), "Photo saved.", Toast.LENGTH_LONG).show();

                                        // Try delete temporary file
                                        File file = new File(currentPhotoPath);
                                        boolean deleted = file.delete();
                                        Log.d(getString(R.string.tag), "file currentPhotoPath: " + currentPhotoPath);
                                        Log.d(getString(R.string.tag), "file deleted: " + deleted);
                                        deleteImage(currentPhotoPath);

                                    } else {

                                        MyAlertDialog dialog = new MyAlertDialog(
                                                Dicer_Activity.this
                                                , "Error"
                                                , "Please report the problems to Tomas Tech."
                                                , new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                            }
                                        }
                                        );
                                    }
                                    layout_alert.setVisibility(View.GONE);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                                .execute();
                    }  catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }

    public void deleteImage(String PhotoPath) {
        String file_dj_path = Environment.getExternalStorageDirectory() + PhotoPath;
        File fdelete = new File(file_dj_path);
        if (fdelete.exists()) {
            if (fdelete.delete()) {
                Log.e("-->", "file Deleted :" + file_dj_path);
                callBroadCast();
            } else {
                Log.e("-->", "file not Deleted :" + file_dj_path);
            }
        }
    }

    public void callBroadCast() {
        if (Build.VERSION.SDK_INT >= 14) {
            Log.e("-->", " >= 14");
            MediaScannerConnection.scanFile(this, new String[]{Environment.getExternalStorageDirectory().toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
                /*
                 *   (non-Javadoc)
                 * @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
                 */
                public void onScanCompleted(String path, Uri uri) {
                    Log.e("ExternalStorage", "Scanned " + path + ":");
                    Log.e("ExternalStorage", "-> uri=" + uri);
                }
            });
        } else {
            Log.e("-->", " < 14");
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                    Uri.parse("file://" + Environment.getExternalStorageDirectory())));
        }
    }


    @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:
                    Intent intent = new Intent(Dicer_Activity.this, Search_ProcessSheet_Lot_Activity.class);
                    startActivity(intent);
                    finish();
                    break;

                case P2:
                    if (Overdue == true){
                        Overdue = false;
                        layout_alert_plan.setVisibility(View.GONE);
                        layout_dicer.setVisibility(View.VISIBLE);

                    }else {
                        if (str_status.trim().equals(ProductionSchedule.STATUS.DICER_WORKING.toString())){
                            if (mode_edit == true){
                                if (map_tools_scan.size() > 0){
                                    if (b_confirm == true) {
                                        Block_button();
                                        Save_Tools(str_dicer_id);
                                    }
                                }else{
                                    Intent i = new Intent(Dicer_Activity.this, Search_ProcessSheet_Lot_Activity.class);
                                    startActivity(i);
                                    finish();
                                }
                            } else { //intent next page output
                                Intent i = new Intent(Dicer_Activity.this, Dicer_Output_Activity.class);
                                startActivity(i);
                                finish();
                            }
                        }else{
                            if (b_confirm == true) {
                                Block_button();
                                Check_completed_data();
                            }
                        }
                    }
                    break;

                case P3:
                    if (str_status.trim().equals(ProductionSchedule.STATUS.DICER_WORKING.toString())){
                        Mode_Edit();
                    }else{
                        dispatchTakePictureIntent();
                    }
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }


}