package com.tomas.ht_mast;

import android.annotation.SuppressLint;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

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

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

import java.util.Arrays;

import cn.pedant.SweetAlert.SweetAlertDialog;
// Needed Imports


public class Photomatching extends Scanner implements View.OnClickListener {

    String t_order, t_part, t_dwg, t_lot_no, t_qty, t_rank, t_box;
    String url_img ;
    TextView txt_commen ,txt_part_name, txt_part_no;
    ImageView imageView;
    JSONObject schedule, label;
    byte[] decode_url;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photomatching);
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);

        txt_commen = (TextView) findViewById(R.id.txt_commen);
        imageView = findViewById(R.id.imageView);
        txt_part_name = (TextView) findViewById(R.id.txt_part_name);
        txt_part_no = (TextView) findViewById(R.id.txt_part_no);
    }

    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
        if (data.trim().equals(""))
            return;
        try {
            Log.d(getString(R.string.tag), "data read:" + data);
            String[] tokens = data.split(getString(R.string.DELIMITER_SCAN_TOKEN),-1);
            Log.d(getString(R.string.tag), Arrays.deepToString(tokens));
            if (tokens.length == 7){//scan label
                t_order = tokens[0].trim();
                t_part = tokens[1].trim();
                t_dwg = tokens[2].trim();
                t_lot_no = tokens[3].trim();
                t_qty = tokens[4].trim();
                t_rank = tokens[5].trim();
                t_box = tokens[6].trim();//key of label
                Log.d(getString(R.string.tag), "token:" + tokens.length);

                txt_commen.setText("Please wait ............");
                Check_Img();
                txt_part_name.setText("Part name :" +t_part);
                txt_part_no.setText("Part no :"+t_dwg);

            }else{
                new SweetAlertDialog(Photomatching.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Invalid QR code!")
                        .show();
            }
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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


    public void Check_Img(){
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "PHOTO/MATCHING/QUERY");
            json.put("parts_no", t_part);
            json.put("check-no-image", "1");

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/ht_api.php",
                    json.toString()) {
                @SuppressLint("StaticFieldLeak")
                @Override
                protected 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), "data " + jsonObject.getString("data"));
                        Log.d(getString(R.string.tag), "status " + jsonObject.getString("status").trim());

                        if (jsonObject.getString("status").trim().equals("success")){
                            url_img = jsonObject.getString("data");
                            ShowImg();

                        }else {
                            txt_commen.setText("There are no photos");
                            new SweetAlertDialog(Photomatching.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("There are no photos.")
                                    .show();
                        }

                    }catch (JSONException e) {
                        txt_commen.setText("There are no photos");
                        url_img ="5555555555";
//                        ShowImg();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            new SweetAlertDialog(Photomatching.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

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

            case R.id.btn_clear:
                imageView.setImageResource(android.R.color.transparent);
                txt_commen.setText("Please scan the label");
                txt_part_no.setText("Part No");
                txt_part_name.setText("Part Name");
                break;
        }
    }


    public void ShowImg(){
        txt_commen.setText("The picture is showing.");
        if(!url_img.equals("")){
            String base64Image = url_img.split(",")[1];
            String encodedDataString = base64Image;
            encodedDataString = encodedDataString.replace("data:image/png;base64,","");

            byte[] imageAsBytes = Base64.decode(encodedDataString.getBytes(), 0);
            imageView.setImageBitmap(BitmapFactory.decodeByteArray(
                    imageAsBytes, 0, imageAsBytes.length));
        }


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

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