package com.tomas.pcs_asi;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.FileProvider;

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.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.pcs_asi.ListData.Get_Item_BOM;
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.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 org.w3c.dom.Text;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class Plasma_Activity extends Scanner implements View.OnClickListener {
    TextView txt_ics_product, txt_job_order, txt_lot_no, txt_user, txt_mag_no, txt_machine, txt_start_plasma, txt_message,
            txt_overdue_title, txt_overdue_dt;
    EditText edt_remark;
    LinearLayout layout_start_plasma, layout_btn_start, layout_btn_finish, layout_remark;
    ConstraintLayout layout_alert_save, layout_alert_plan;
    ScrollView scrollview;
    String str_process, str_status, str_sch_id, str_ics, str_job, str_lot, str_mag_no, str_machine, str_overdue_dt, str_overdue_title,
            str_start, dt_to_photo, dt_to_server, str_item_type;
    boolean Overdue, b_confirm;
    Calendar calendar;
    private static final int REQUEST_IMAGE_CAPTURE = 200;
    public static final int SIGN_INVOICE_ACTIVITY = 100;
    public static final int SIGN_DO_ACTIVITY = 101;
    SimpleDateFormat fm_dt_server, fm_dt_photo;
    Button btn_start_plasma, btn_finish_plasma;
    Map<String, Get_Machine> map_machine;

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

        Overdue = false;
        b_confirm = true;
        map_machine = new LinkedHashMap<>();

        scrollview = (ScrollView)findViewById(R.id.scrollview);
        layout_start_plasma = (LinearLayout) findViewById(R.id.layout_start_plasma);
        layout_btn_start = (LinearLayout) findViewById(R.id.layout_btn_start);
        layout_btn_finish = (LinearLayout) findViewById(R.id.layout_btn_finish);
        layout_remark = (LinearLayout) findViewById(R.id.layout_remark);
        layout_alert_save = (ConstraintLayout)findViewById(R.id.layout_alert_save);
        layout_alert_plan = (ConstraintLayout) findViewById(R.id.layout_alert_plan);

        txt_ics_product = (TextView) findViewById(R.id.txt_ics_product);
        txt_job_order = (TextView) findViewById(R.id.txt_job_order);
        txt_lot_no = (TextView) findViewById(R.id.txt_lot_no);
        txt_user = (TextView) findViewById(R.id.txt_user);
        txt_mag_no = (TextView) findViewById(R.id.txt_mag_no);
        txt_machine = (TextView) findViewById(R.id.txt_machine);
        txt_start_plasma = (TextView) findViewById(R.id.txt_start_plasma);
        txt_message = (TextView) findViewById(R.id.txt_message);
        txt_overdue_title = (TextView) findViewById(R.id.txt_overdue_title);
        txt_overdue_dt = (TextView) findViewById(R.id.txt_overdue_dt);

        btn_start_plasma = (Button)findViewById(R.id.btn_start_plasma);
        btn_finish_plasma = (Button)findViewById(R.id.btn_finish_plasma);

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

        str_process = Settings.getPROCESS();
        str_status  = Settings.getSTATUS();
        str_overdue_dt  = Settings.getOverdueDt();
        str_overdue_title = Settings.getOverdueTitle();
        str_sch_id = Settings.getSchId();
        str_ics = Settings.getICS();
        str_job = Settings.getJobOrder();
        str_lot = Settings.getLotNo();
        str_mag_no = Settings.getMagNo();
        str_item_type = Settings.getItemType();
        Log.d(getString(R.string.tag), "PLASMA Activity : " + str_process+" | "+ str_status+ " | "+str_overdue_dt+"|"+str_mag_no+"|"+str_item_type);

        txt_ics_product.setText("ICS : "+str_ics);
        txt_job_order.setText("JOB ORDER : "+str_job);
        txt_lot_no.setText("LOT NO : "+str_lot);

        Get_Machine("PLASMA", str_item_type);

        if (str_overdue_dt.trim().equals("")||str_overdue_dt.trim().equals("null")){
            Overdue = false;
            layout_alert_plan.setVisibility(View.GONE);
            scrollview.setVisibility(View.VISIBLE);

        }else{
            Overdue = true;
            scrollview.setVisibility(View.GONE);
            layout_alert_plan.setVisibility(View.VISIBLE);
            txt_overdue_title.setText(str_overdue_title);
            txt_overdue_dt.setText(str_overdue_dt);
        }

        if (str_status.trim().equals(ProductionSchedule.STATUS.PLASMA.toString())){
            layout_start_plasma.setVisibility(View.VISIBLE);
            layout_remark.setVisibility(View.VISIBLE);
            layout_btn_start.setVisibility(View.GONE);
            layout_btn_finish.setVisibility(View.VISIBLE);
            str_machine = Settings.getMACHINE();
            str_start = Settings.getStartDt();

            txt_machine.setText(str_machine);
            txt_machine.setBackgroundResource(R.drawable.img_backgroup);
            txt_start_plasma.setText(str_start);
            Log.d(getString(R.string.tag), "PLASMA : " + str_machine+ " | "+str_start);
        }

    }

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

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

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

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

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

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

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

    private void Unblock_button() {
        b_confirm = true;
        btn_start_plasma.setEnabled(true);
        btn_start_plasma.setBackgroundResource(R.drawable.button_backgroup_green);
        btn_finish_plasma.setEnabled(true);
        btn_finish_plasma.setBackgroundResource(R.drawable.button_backgroup_green);
    }

    private void Clear_text() {
        txt_user.setText("");
        txt_machine.setText("");
        txt_mag_no.setText("");
    }

    @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);
            String str_scan = data.trim();

            Log.d(getString(R.string.tag), "scan data : " + data.trim().substring(0,2));

               if (str_scan.contains("PLASMA")) {
                   if (str_status.trim().equals(ProductionSchedule.STATUS.PLASMA.toString())){
                       new SweetAlertDialog(Plasma_Activity.this, SweetAlertDialog.WARNING_TYPE)
                               .setTitleText("แจ้งเตือน")
                               .setContentText("ไม่สามารถเปลี่ยนเครื่องจักรได้!")
                               .show();
                   }else {
                       if (map_machine.containsKey(str_scan)) {
                           txt_machine.setText(str_scan);
                       }else {
                           new SweetAlertDialog(Plasma_Activity  .this, SweetAlertDialog.WARNING_TYPE)
                                   .setTitleText("แจ้งเตือน")
                                   .setContentText("ไม่พบเครื่องจักร")
                                   .show();
                       }
                   }

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

               } else if (str_scan.length() == 4){
                   if (str_status.trim().equals(ProductionSchedule.STATUS.PLASMA.toString())){
                       txt_mag_no.setText(str_scan);
                   }else {
                       if (str_scan.trim().equals(str_mag_no)) {
                           txt_mag_no.setText(str_scan);

                       } else {
                           new SweetAlertDialog(Plasma_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                   .setTitleText("แจ้งเตือน")
                                   .setContentText("........Mag No. ไม่ตรงกัน !........ "+" Mag No. = "+str_mag_no)
                                   .show();
                       }
                   }
               }else{
                   new SweetAlertDialog(Plasma_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 update_plasma() {
        if (txt_user.getText().toString().trim().equals("")
           || txt_mag_no.getText().toString().trim().equals("")
           || txt_machine.getText().toString().trim().equals("")){

            Unblock_button();
            new SweetAlertDialog(Plasma_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("กรุณากรอกข้อมูลให้ครบ!")
                    .show();

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

            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 {
                JSONObject json = new JSONObject();
                json.put("cmd", "update_plasma");
                json.put("mag_no", txt_mag_no.getText().toString().trim());
                json.put("machine", txt_machine.getText().toString().trim());
                json.put("user_id", txt_user.getText().toString().trim());
                json.put("act_dt", dt_to_server);
                json.put("sch_id", str_sch_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(Plasma_Activity.this,R.string.insert,Toast.LENGTH_SHORT).show();

                                finish();

                            } else {
                                layout_alert_save.setVisibility(View.GONE);
                                Unblock_button();
                                new SweetAlertDialog(Plasma_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR")
                                        .setContentText("Can't update ProductionPlan")
                                        .show();
                            }
                        } catch (JSONException e) {
                            layout_alert_save.setVisibility(View.GONE);
                            Unblock_button();
                            new SweetAlertDialog(Plasma_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(e.getMessage())
                                    .show();
                        }
                    }
                }.execute();
            } catch (Exception e) {
                Unblock_button();
                layout_alert_save.setVisibility(View.GONE);
                new SweetAlertDialog(Plasma_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
        }
    }

    private void update_plasma_end() {
        if (txt_user.getText().toString().trim().equals("")
           || txt_mag_no.getText().toString().trim().equals("")) {

            Unblock_button();
            new SweetAlertDialog(Plasma_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Please complete the information")
                    .show();
        }else {
            layout_alert_save.setVisibility(View.VISIBLE);
            txt_message.setText("กรุณารอสักครู่ กำลังบันทึกข้อมูล...");

            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 {
                String remark = edt_remark.getText().toString().trim();
                String encode = URLEncoder.encode(remark,"UTF-8");

                JSONObject json = new JSONObject();
                json.put("cmd", "update_finish_plasma");
                json.put("user_id", txt_user.getText().toString().trim());
                json.put("mag_no", txt_mag_no.getText().toString().trim());
                json.put("remark",encode);
                json.put("act_dt", dt_to_server);
                json.put("sch_id", str_sch_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(Plasma_Activity.this,R.string.insert,Toast.LENGTH_SHORT).show();
                                finish();

                            } else {
                                Unblock_button();
                                layout_alert_save.setVisibility(View.GONE);
                                new SweetAlertDialog(Plasma_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                        .setTitleText("ERROR")
                                        .setContentText("Can't update ProductionPlan")
                                        .show();
                            }
                        } catch (JSONException e) {
                            Unblock_button();
                            layout_alert_save.setVisibility(View.GONE);
                            new SweetAlertDialog(Plasma_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(e.getMessage())
                                    .show();
                        }
                    }
                }.execute();
            } catch (Exception e) {
                Unblock_button();
                layout_alert_save.setVisibility(View.GONE);
                new SweetAlertDialog(Plasma_Activity.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("ERROR")
                        .setContentText(e.getMessage())
                        .show();
            }
        }
    }

    private void Get_Machine(String unit, String type) {
        map_machine.clear();
        try {
            layout_alert_save.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_save.setVisibility(View.GONE);
                            SweetAlertDialog d = new SweetAlertDialog(Plasma_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_save.setVisibility(View.GONE);
                        }
                        Log.d(getString(R.string.tag), String.valueOf(map_machine.size()));
                    }catch (JSONException e) {
                        layout_alert_save.setVisibility(View.GONE);
                        new SweetAlertDialog(Plasma_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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


    private void Check_User(String data) {
        if (Settings.getMap_user().containsKey(data)){
            txt_user.setText(data);
            if (Settings.getMap_user().get(data).getPlasma().trim().equals("1")) {
                txt_user.setText(data);

            }else {
                txt_user.setText("");
                new SweetAlertDialog(Plasma_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("แจ้งเตือน")
                        .setContentText("ไม่อนุญาตให้ทำงานใน Plasma")
                        .show();
            }

        }else {
            txt_user.setText("");
            new SweetAlertDialog(Plasma_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("แจ้งเตือน")
                    .setContentText("ไม่พบรหัสพนักงาน!")//OK
                    .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_save.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 = "PLASMA"+"_"+str_lot+"_"+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(
                                                Plasma_Activity.this
                                                , "Error"
                                                , "Please report the problems to Tomas Tech."
                                                , new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                            }
                                        }
                                        );
                                    }
                                    layout_alert_save.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(Plasma_Activity.this, Search_ProcessSheet_Activity.class);
                    startActivity(intent);
                    finish();
                    break;

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

                    }else {
                        if (str_status.trim().equals(ProductionSchedule.STATUS.PLASMA.toString())) {
                           //finish plasma
                            if (b_confirm == true) {
                                Block_button();
                                update_plasma_end();
                            }
                        } else {
                            // start plasma
                            if (b_confirm == true) {
                                Block_button();
                                update_plasma();
                            }
                        }
                    }
                    break;

                case P3:
                    dispatchTakePictureIntent();
                    break;

                case P4:
                    Clear_text();
                    break;
            }
        }

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