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.annotation.SuppressLint;
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.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.net.URLEncoder;
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 Oven_Activity extends Scanner implements View.OnClickListener {
    TextView txt_header, txt_user, txt_ics, txt_job_order, txt_lot_no, txt_mag_no, txt_machine, txt_overdue_title, txt_overdue_dt, txt_message,
             txt_start_oven, txt_header_mag_no;
    String str_process, str_ics, str_job_order, str_lot_no, str_mc_type, str_oven_id, str_status,dt_to_photo,dt_to_server, str_machine, str_start,
           OVEN_DB_PLAN_START, OVEN_DB_PLAN_END,SCH_ID, ICS, JOB_ORDER, LOT_NO, MAG_NO, PROCESS, STATUS, dt_format = "yyyy-MM-dd HH:mm:ss",
           OVEN_MOLD_PLAN_START, OVEN_MOLD_PLAN_END, str_item_type;
    EditText edt_remark;
    RecyclerView view_oven;
    Calendar calendar;
    SimpleDateFormat fm_dt_server, fm_dt_photo;
    Oven_Adapter oven_adapter;
    private static final int REQUEST_IMAGE_CAPTURE = 200;
    public static final int SIGN_INVOICE_ACTIVITY = 100;
    public static final int SIGN_DO_ACTIVITY = 101;
    int scan = 0;
    ConstraintLayout layout_alert_plan,layout_alert;
    LinearLayout layout_oven, layout_oven_input, oven_confirm, layout_btn_confirm, layout_btn_start, oven_output, layout_btn_finish,
            layout_mag_no;
    boolean Overdue, confirmed, b_confirm;
    Map<String, Item_Oven>map_item_oven;
    List<Item_Oven> list_oven;
    Button btn_start_oven, btn_finish_oven;
    Map<String, Get_Machine> map_machine;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_oven);
        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");

        confirmed = false;
        b_confirm = true;

        map_item_oven = new LinkedHashMap<>();
        map_machine = new LinkedHashMap<>();
        list_oven = new ArrayList<Item_Oven>();

        layout_oven = (LinearLayout)findViewById(R.id.layout_oven);
        layout_alert_plan = (ConstraintLayout)findViewById(R.id.layout_alert_plan);
        layout_alert = (ConstraintLayout)findViewById(R.id.layout_alert);
        layout_oven_input = (LinearLayout)findViewById(R.id.oven_input);
        oven_confirm = (LinearLayout)findViewById(R.id.oven_confirm);
        layout_btn_confirm = (LinearLayout)findViewById(R.id.layout_btn_confirm);
        layout_btn_start = (LinearLayout)findViewById(R.id.layout_btn_start);
        layout_btn_finish = (LinearLayout)findViewById(R.id.layout_btn_finish);
        layout_mag_no = (LinearLayout)findViewById(R.id.layout_mag_no);
        oven_output = (LinearLayout)findViewById(R.id.oven_output);

        edt_remark = (EditText)findViewById(R.id.edt_remark);

        btn_finish_oven = (Button)findViewById(R.id.btn_finish_oven);
        btn_start_oven = (Button)findViewById(R.id.btn_start_oven);

        txt_header = (TextView)findViewById(R.id.txt_header);
        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_mag_no = (TextView)findViewById(R.id.txt_mag_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_start_oven = (TextView)findViewById(R.id.txt_start_oven);
        txt_message = (TextView)findViewById(R.id.txt_message);
        txt_header_mag_no = (TextView)findViewById(R.id.txt_header_mag_no);

        view_oven = (RecyclerView)findViewById(R.id.view_oven);
        view_oven.setHasFixedSize(true);
        view_oven.setRecycledViewPool(new RecyclerView.RecycledViewPool());
        view_oven.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        view_oven.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        view_oven.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_header.setText(str_process);
        txt_ics.setText(str_ics);
        txt_job_order.setText(str_job_order);
        txt_lot_no.setText(str_lot_no);

        Get_Machine(str_mc_type, str_item_type);

        //check process
        if (str_process.trim().equals(ProductionSchedule.PROCESS.OVEN_MOLD.toString())){
            layout_mag_no.setVisibility(View.INVISIBLE);
            txt_header_mag_no.setVisibility(View.GONE);
        }

        //check status
        if (str_status.trim().equals(ProductionSchedule.STATUS.DIE_BOND_WAIT.toString()) ||
            str_status.trim().equals(ProductionSchedule.STATUS.MOLD_WAIT.toString())) {
            Check_ProcessSheet();

        }else{
            //status == oven
            str_oven_id = Settings.getOvenId();
            Log.d(getString(R.string.tag), "Oven ID : " + str_oven_id);

            if (str_process.trim().equals(ProductionSchedule.PROCESS.OVEN_DIE_BOND.toString())){
                Search_ProcessSheet_BD(str_oven_id);

            }else if (str_process.trim().equals(ProductionSchedule.PROCESS.OVEN_MOLD.toString())){
                Search_ProcessSheet_MOLD(str_oven_id);
            }

            txt_machine.setBackgroundResource(R.drawable.img_backgroup);
            layout_oven_input.setVisibility(View.GONE);
            layout_btn_confirm.setVisibility(View.GONE);
            oven_output.setVisibility(View.VISIBLE);
            layout_btn_finish.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imb_back:
                if (confirmed == true){
                    Return_View();

                }else {
                    Finish_Activity();
                }
                break;

            case R.id.btn_clear:
                Clear_view();
                break;

            case R.id.btn_confirm:
                Confirm();
                break;

            case R.id.btn_ok:
                Overdue = false;
                layout_alert_plan.setVisibility(View.GONE);
                layout_oven.setVisibility(View.VISIBLE);
                break;

            case R.id.btn_start_oven:
                //   //take photo start oven
                if (b_confirm == true) {
                    Block_button();
                    dispatchTakePictureIntent();
                }
                break;

            case R.id.btn_finish_oven:
                //update finish oven
                if(b_confirm == true) {
                    Block_button();
                    if (str_process.trim().equals(ProductionSchedule.PROCESS.OVEN_DIE_BOND.toString())) {
                        Update_Finish_Oven_DB();
                    } else if (str_process.trim().equals(ProductionSchedule.PROCESS.OVEN_MOLD.toString())) {
                        Update_Finish_Oven_Mold();
                    }
                }
                break;
        }
    }

    private void Block_button() {
        b_confirm = false;
        btn_start_oven.setEnabled(false);
        btn_start_oven.setBackgroundResource(R.drawable.button_backgroup_gray);
        btn_finish_oven.setEnabled(false);
        btn_finish_oven.setBackgroundResource(R.drawable.button_backgroup_gray);
    }

    private void Unblock_button() {
        b_confirm = true;
        btn_start_oven.setEnabled(true);
        btn_start_oven.setBackgroundResource(R.drawable.button_backgroup_green);
        btn_finish_oven.setEnabled(true);
        btn_finish_oven.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), "scan data : " + data);
            if (str_status.trim().equals(ProductionSchedule.STATUS.DIE_BOND_WAIT.toString())||//check status for lock scanner
                str_status.trim().equals(ProductionSchedule.STATUS.MOLD_WAIT.toString())) {
                if (confirmed == false) {
                    if (scan == 0) {
                        if (data.trim().length() == 4) {
                            //check_mag_no();
                            if (data.trim().equals(MAG_NO)) {
                                txt_mag_no.setText(data.trim());
                                Add_mapItem();

                            } else {
                                new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("แจ้งเตือน")
                                        .setContentText("..........Mag No. ไม่ตรงกัน  !.......... "+" Mag No. = "+MAG_NO)
                                        .show();
                            }
                        } else if (data.trim().contains(str_mc_type)) {//machine
                            if (map_machine.containsKey(data.trim())){
                                txt_machine.setText(data.trim());

                            }else {
                                new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("แจ้งเตือน")
                                        .setContentText("ไม่พบเครื่องจักร")
                                        .show();

                            }
                        } else if (data.trim().length() == 6) {//user
                            Check_User(data.trim());

                        } else if (data.trim().length() == 10) {//ics code
                            if (map_item_oven.size() == 4 && str_process.trim().equals(ProductionSchedule.PROCESS.OVEN_DIE_BOND.toString())) {
                                new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("แจ้งเตือน")
                                        .setContentText("ใส่ได้มากสุด 4 process sheet!")
                                        .show();
                            } else {
                                txt_ics.setText(data.trim());
                                txt_job_order.setText("");
                                txt_lot_no.setText("");
                                txt_mag_no.setText("");
                                scan = 1;
                            }

                        } else {
                            new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("แจ้งเตือน")
                                    .setContentText("QR code ไม่ถูกต้อง!")
                                    .show();
                        }
                    } else if (scan == 1) {
                        scan = 2;
                        txt_job_order.setText(data.trim());

                    } else {
                        scan = 0;
                        txt_lot_no.setText(data.trim());
                        Check_ProcessSheet();
                    }
                } else {
                    new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("ไม่สามารถสแกน process sheet ได้!")
                            .show();
                }
            }else{// oven --> finish oven
                if (data.trim().length() == 6) {//user
                    Check_User(data.trim());

                }else {
                    new SweetAlertDialog(Oven_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 Add_mapItem() {
        Log.d(getString(R.string.tag), "Add_mapItem: " + String.valueOf(map_item_oven.size()));
            //add map
            map_item_oven.put(SCH_ID, new Item_Oven(
                    SCH_ID,
                    ICS,
                    JOB_ORDER,
                    LOT_NO,
                    MAG_NO));
            Log.d(getString(R.string.tag), "else: " + String.valueOf(map_item_oven.size()));
        Set_view_oven();
    }
    private void Set_view_oven() {
        //set view
        list_oven.clear();
        for (String key : map_item_oven.keySet()) {
            Item_Oven item = map_item_oven.get(key);
            list_oven.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_oven: " + String.valueOf(list_oven.size()));
        oven_adapter = new Oven_Adapter(list_oven, Oven_Activity.this,str_process);
        view_oven.setAdapter(oven_adapter);
        Reset_view();

    }

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

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

            JSONObject json = new JSONObject();
            json.put("cmd", "search_oven_mold");
            json.put("oven_id", oven_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(Oven_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Oven ID : "+oven_id+" not found!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                list_oven.add(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(),
                                        ""));
//                                        jArray.getJSONObject(i).getString("oven_diebond_mag_no").trim()));
                            }
                            JSONObject obj = jArray.getJSONObject(0);
                            JSONObject array_start_dt = obj.getJSONObject("oven_mold_act_start_dt");
                            str_start = array_start_dt.getString("date");
                            str_start = str_start.substring(0,19);
                            Log.d(getString(R.string.tag), "OVEN_START: " + str_start);
                            str_machine = jArray.getJSONObject(0).getString("oven_mold_machine").trim();

                            txt_machine.setText(str_machine);
                            txt_start_oven.setText(str_start);
                            oven_adapter = new Oven_Adapter(list_oven, Oven_Activity.this,str_process);
                            view_oven.setAdapter(oven_adapter);
                            layout_alert.setVisibility(View.GONE);
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }
    private void Search_ProcessSheet_BD(String oven_id) {
        list_oven.clear();
        try {
            layout_alert.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังค้นหาข้อมูล...");

            JSONObject json = new JSONObject();
            json.put("cmd", "search_oven_db");
            json.put("oven_id", oven_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(Oven_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Oven ID : "+oven_id+" not found!")
                                    .show();
                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                list_oven.add(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(),
                                        jArray.getJSONObject(i).getString("oven_diebond_mag_no").trim()));
                            }

                            JSONObject obj = jArray.getJSONObject(0);
                            JSONObject array_start_dt = obj.getJSONObject("oven_diebond_act_start_dt");
                            str_start = array_start_dt.getString("date");
                            str_start = str_start.substring(0,19);
                            Log.d(getString(R.string.tag), "OVEN_START: " + str_start);
                            str_machine = jArray.getJSONObject(0).getString("oven_diebond_machine").trim();

                            txt_machine.setText(str_machine);
                            txt_start_oven.setText(str_start);
                            oven_adapter = new Oven_Adapter(list_oven, Oven_Activity.this,str_process);
                            view_oven.setAdapter(oven_adapter);
                            layout_alert.setVisibility(View.GONE);
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    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(Oven_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 = jArray.getJSONObject(i).getString("ICSProductCode").trim();
                                 JOB_ORDER = jArray.getJSONObject(i).getString("job_order").trim();
                                 LOT_NO = jArray.getJSONObject(i).getString("lot_no").trim();
                                 MAG_NO = jArray.getJSONObject(i).getString("diebond_mag_no").trim() == "null" ? "" : jArray.getJSONObject(i).getString("diebond_mag_no").trim();;

                                JSONObject obj = jArray.getJSONObject(i);
                                JSONObject array_start_dt = obj.getJSONObject("oven_diebond_plan_start_dt");
                                OVEN_DB_PLAN_START = array_start_dt.getString("date");
                                OVEN_DB_PLAN_START = OVEN_DB_PLAN_START.substring(0,19);
                                Log.d(getString(R.string.tag), "OVEN_DB_PLAN_START: " + OVEN_DB_PLAN_START);

                                JSONObject array_end_dt = obj.getJSONObject("oven_diebond_plan_end_dt");
                                OVEN_DB_PLAN_END = array_end_dt.getString("date");
                                OVEN_DB_PLAN_END = OVEN_DB_PLAN_END.substring(0,19);
                                Log.d(getString(R.string.tag), "OVEN_DB_PLAN_END: " + OVEN_DB_PLAN_END);

                                JSONObject array_mold_start_dt = obj.getJSONObject("oven_mold_plan_start_dt");
                                OVEN_MOLD_PLAN_START = array_mold_start_dt.getString("date");
                                OVEN_MOLD_PLAN_START = OVEN_MOLD_PLAN_START.substring(0,19);
                                Log.d(getString(R.string.tag), "OVEN_MOLD_PLAN_START: " + OVEN_MOLD_PLAN_START);

                                JSONObject array_mold_end_dt = obj.getJSONObject("oven_mold_plan_end_dt");
                                OVEN_MOLD_PLAN_END = array_mold_end_dt.getString("date");
                                OVEN_MOLD_PLAN_END = OVEN_MOLD_PLAN_END.substring(0,19);
                                Log.d(getString(R.string.tag), "OVEN_DB_PLAN_END: " + OVEN_MOLD_PLAN_END);
                            }
                            Log.d(getString(R.string.tag), "mag_no: " + MAG_NO+" STATUS:"+STATUS);
                            Check_status();
                            layout_alert.setVisibility(View.GONE);
                        }
                    }catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e) {
            layout_alert.setVisibility(View.GONE);
            new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

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

            map_item_oven.remove(SCH_ID);
            Set_view_oven();
            Reset_view();

        }else {
            if (PROCESS.trim().equals(ProductionSchedule.PROCESS.OVEN_DIE_BOND.toString())) {
                if (STATUS.trim().equals(ProductionSchedule.STATUS.DIE_BOND_WAIT.toString())) {
                    Check_Overdue(OVEN_DB_PLAN_START, "Start Plan OVEN DIE BOND");

//                } else if (STATUS.trim().equals(ProductionSchedule.STATUS.DIE_BOND_OVEN.toString())) {
////                    Check_Overdue(OVEN_DB_PLAN_END, "Finish Plan OVEN DIE BOND");

                } else {
                    Reset_view();
                    new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("This ProcessSheet "+STATUS)
                            .show();
                }
            } else if (PROCESS.trim().equals(ProductionSchedule.PROCESS.OVEN_MOLD.toString())) {
                if (STATUS.trim().equals(ProductionSchedule.STATUS.MOLD_WAIT.toString())) {
                    Check_Overdue(OVEN_MOLD_PLAN_START, "Start Plan OVEN MOLD");

//                } else if (STATUS.trim().equals(ProductionSchedule.STATUS.MOLD_OVEN.toString())) {
//                    Check_Overdue(OVEN_MOLD_PLAN_END, "Finish Plan OVEN MOLD");

                } else {
                    Reset_view();
                    new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("แจ้งเตือน")
                            .setContentText("This ProcessSheet "+STATUS)
                            .show();
                }

            } else {
                new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("This ProcessSheet "+STATUS)
                        .show();
                Reset_view();
            }
        }
    }

    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_oven.setVisibility(View.GONE);

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

        }

        if (str_status.trim().equals(ProductionSchedule.STATUS.MOLD_WAIT.toString())){
            Add_mapItem();
        }
    }

    private void Check_User(String data) {
        if (Settings.getMap_user().containsKey(data)){
            if (str_process.trim().equals(ProductionSchedule.PROCESS.OVEN_DIE_BOND.toString())
                    && Settings.getMap_user().get(data).getOven_diebond().trim().equals("1")) {
                txt_user.setText(data);

            }else if (str_process.trim().equals(ProductionSchedule.PROCESS.OVEN_MOLD.toString())
                    && Settings.getMap_user().get(data).getOven_mold().trim().equals("1")) {
                txt_user.setText(data);

            }else {
                txt_user.setText("");
                new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("ไม่อนุญาตให้ทำงานใน "+str_process)
                        .show();
            }
        }else {
            txt_user.setText("");
            new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("ไม่พบรหัสพนักงาน!")//OK
                    .show();
        }
    }
    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(Oven_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(Oven_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void Confirm() {
        if (map_item_oven.size() == 0 ||
            txt_user.getText().toString().trim().equals("") ||
            txt_machine.getText().toString().trim().equals("")) {

            new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณากรอกข้อมูลให้ครบ!")
                    .show();
        }else{
            confirmed = true;
            txt_machine.setBackgroundResource(R.drawable.img_backgroup);
            txt_user.setBackgroundResource(R.drawable.img_backgroup);
            layout_oven_input.setVisibility(View.GONE);
            layout_btn_confirm.setVisibility(View.GONE);
            layout_btn_start.setVisibility(View.VISIBLE);
        }
    }

    private void Clear_view() {
        scan = 0;
        map_item_oven.clear();
        txt_user.setText("");
        txt_ics.setText("");
        txt_job_order.setText("");
        txt_lot_no.setText("");
        txt_mag_no.setText("");
        txt_machine.setText("");
        Set_view_oven();
    }
    private void Update_Oven_mold() {
        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);
        //update

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

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

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

                Map<String, String> jsonParams = new HashMap<>();
                jsonParams.put("sch_id", item.getSch_id());
                jsonParams.put("oven_id", txt_machine.getText().toString().trim()+dt_to_photo);
                jsonParams.put("machine", txt_machine.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("oven_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) {
                            Toast.makeText(Oven_Activity.this,R.string.insert,Toast.LENGTH_SHORT).show();
//                            Finish_Activity();
                            finish();
                        } else {
                            layout_alert.setVisibility(View.GONE);
                            Unblock_button();
                            new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Can't update ProductionPlan")
                                    .show();
                        }
                    } catch (JSONException e) {
                        layout_alert.setVisibility(View.GONE);
                        Unblock_button();
                        new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        } catch (Exception e) {
            layout_alert.setVisibility(View.GONE);
            Unblock_button();
            new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Update_Oven_db() {
        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);
            //update

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

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

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

                    Map<String, String> jsonParams = new HashMap<>();
                    jsonParams.put("sch_id", item.getSch_id());
                    jsonParams.put("oven_id", txt_machine.getText().toString().trim()+dt_to_photo);
                    jsonParams.put("machine", txt_machine.getText().toString().trim());
                    jsonParams.put("user_id", txt_user.getText().toString().trim());
                    jsonParams.put("mag_no",item.getMag_no());
                    jsonParams.put("act_dt", dt_to_server);

                    JSONObject jsonObject = new JSONObject(jsonParams);
                    jsonArray.put(jsonObject);
                }
                json.put("oven_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) {
                                Toast.makeText(Oven_Activity.this,R.string.insert,Toast.LENGTH_SHORT).show();
//                                Finish_Activity();
                                finish();

                            } else {
                                layout_alert.setVisibility(View.GONE);
                                Unblock_button();
                                new SweetAlertDialog(Oven_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(Oven_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(e.getMessage())
                                    .show();
                        }
                    }
                }.execute();
            } catch (Exception e) {
                Unblock_button();
                layout_alert.setVisibility(View.GONE);
                new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
    }

    private void Update_Finish_Oven_Mold() {
        if (txt_user.getText().toString().trim().equals("")){
            Unblock_button();
            new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกนรหัสพนักงาน!")
                    .show();
        }else{
            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("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

                String remark = edt_remark.getText().toString().trim();
                String encode = URLEncoder.encode(remark,"UTF-8");

                JSONObject json = new JSONObject();
                json.put("cmd", "update_finish_oven_mold");
                json.put("remark", encode);
                json.put("user_id", txt_user.getText().toString().trim());
                json.put("act_dt", dt_to_server);
                json.put("oven_id", str_oven_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 {
                            JSONObject jsonObject = new JSONObject(response);
                            String status = jsonObject.getString("status");
                            int affected_rows = jsonObject.getInt("affected_rows");

                            if (status.equals("success") && affected_rows > 0) {
                                Toast.makeText(Oven_Activity.this,R.string.insert,Toast.LENGTH_SHORT).show();
//                                Finish_Activity();
                                finish();

                            } else {
                                layout_alert.setVisibility(View.GONE);
                                Unblock_button();
                                new SweetAlertDialog(Oven_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(Oven_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(e.getMessage())
                                    .show();
                        }
                    }
                }.execute();
            } catch (Exception e) {
                Unblock_button();
                layout_alert.setVisibility(View.GONE);
                new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
        }
    }


    private void Update_Finish_Oven_DB() {
        if (txt_user.getText().toString().trim().equals("")){
            Unblock_button();
            new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณาสแกนรหัสพนักงาน!")
                    .show();
        }else{
            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("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

                String remark = edt_remark.getText().toString().trim();
                String encode = URLEncoder.encode(remark,"UTF-8");

                JSONObject json = new JSONObject();
                json.put("cmd", "update_finish_oven_db");
                json.put("remark", encode);
                json.put("user_id", txt_user.getText().toString().trim());
                json.put("act_dt", dt_to_server);
                json.put("oven_id", str_oven_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 {
                            JSONObject jsonObject = new JSONObject(response);
                            String status = jsonObject.getString("status");
                            int affected_rows = jsonObject.getInt("affected_rows");

                            if (status.equals("success") && affected_rows > 0) {
                                Toast.makeText(Oven_Activity.this,R.string.insert,Toast.LENGTH_SHORT).show();
//                                Finish_Activity();
                                finish();

                            } else {
                                Unblock_button();
                                layout_alert.setVisibility(View.GONE);
                                new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR")
                                        .setContentText("Can't update ProductionPlan")
                                        .show();
                            }
                        } catch (JSONException e) {
                            layout_alert.setVisibility(View.GONE);
                            Unblock_button();
                            new SweetAlertDialog(Oven_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(e.getMessage())
                                    .show();
                        }
                    }
                }.execute();
            } catch (Exception e) {
                layout_alert.setVisibility(View.GONE);
                Unblock_button();
                new SweetAlertDialog(Oven_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();
        }
        Unblock_button();
    }

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

    @SuppressLint("StaticFieldLeak")
    @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 = 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);

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

                                        Log.d(getString(R.string.tag), "process: " + str_process);
                                        if (str_process.trim().equals(ProductionSchedule.PROCESS.OVEN_DIE_BOND.toString())){
                                            Update_Oven_db();
                                        }else if(str_process.trim().equals(ProductionSchedule.PROCESS.OVEN_MOLD.toString())){
                                            Update_Oven_mold();
                                        }

                                    } else {

                                        MyAlertDialog dialog = new MyAlertDialog(
                                                Oven_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();
                                    Log.d(getString(R.string.tag), "catch:1 ");
                                }
                            }
                        }
                                .execute();
                    }  catch (JSONException e) {
                        e.printStackTrace();
                        Log.d(getString(R.string.tag), "catch:2 ");
                    }
                }
                break;
        }
        Unblock_button();
    }

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

    private void Finish_Activity() {
        Intent intent = new Intent(Oven_Activity.this, Search_ProcessSheet_Lot_Activity.class);
        startActivity(intent);
        finish();
    }
    private void Return_View() {
        confirmed = false;
        txt_machine.setBackgroundResource(R.drawable.button_backgroup_menu);
        txt_user.setBackgroundResource(R.drawable.button_backgroup_menu);
        layout_oven_input.setVisibility(View.VISIBLE);
        layout_btn_confirm.setVisibility(View.VISIBLE);
        layout_btn_start.setVisibility(View.GONE);
    }

    @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:
                    if (confirmed == true){
                        Return_View();

                    }else {
                        Finish_Activity();
                    }
                    break;

                case P2:
                    if (str_status.trim().equals(ProductionSchedule.STATUS.DIE_BOND_WAIT.toString())||
                        str_status.trim().equals(ProductionSchedule.STATUS.MOLD_WAIT.toString())) {
                        if (Overdue == true) {
                            Overdue = false;
                            layout_alert_plan.setVisibility(View.GONE);
                            layout_oven.setVisibility(View.VISIBLE);
                        } else if (confirmed == true) {
                            //take photo start oven
                            if (b_confirm == true) {
                                Block_button();
                                dispatchTakePictureIntent();
                            }
                        } else {
                            Confirm();
                        }
                    }else {
                        if(b_confirm == true) {
                            Block_button();
                            if (str_process.trim().equals(ProductionSchedule.PROCESS.OVEN_DIE_BOND.toString())) {
                                Update_Finish_Oven_DB();
                            } else if (str_process.trim().equals(ProductionSchedule.PROCESS.OVEN_MOLD.toString())) {
                                Update_Finish_Oven_Mold();
                            }
                        }
                    }
                    break;

                case P3:
                    Clear_view();
                    break;
            }
        }
        return super.onKeyUp(keyCode, event);
    }
}