package kr.co.compcareworker.Fragment.Plan;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;

import info.mqtt.android.service.Ack;
import info.mqtt.android.service.MqttAndroidClient;
import kr.co.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Activity.MainActivity;
import kr.co.compcareworker.Data.Company.Machine.Product.MonitoringData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.Common;

@SuppressLint("ValidFragment")
public class Deal_Fragment extends Fragment {
    private Handler handler, hdr;
    String iv_idx;
    String url;
    String web_Invoice_URL = "sell/invoice/preview/";
    String web_Url = "?mode=1&app_mode=Y";

    FragmentActivity fa;

    WebView webView;
    LinearLayout ll_act_deal_detail_signature, ll_act_deal_detail_signature_layout, ll_act_deal_detail_email_layout;
    TextView tv_act_deal_detail_enter, tv_act_deal_detail_complete, tv_act_deal_detail_send;
    EditText et_act_deal_detail_email;
    ProgressBar progress;
    MqttAndroidClient mqttAndroidClient;
    //    MqttAndroidClient mqttAndroidClient;
    String mc_iot_mac;
    boolean mqtt_init_success = false;
    Thread timer_thread;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        fa = (FragmentActivity) getActivity();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        fa = null;
        Common.getInstance().setDirEmpty(getContext(), "/CompcareWorker");
    }

    @SuppressLint("ValidFragment")
    public Deal_Fragment(Handler handler, String iv_idx, String mc_iot_mac) {
        this.handler = handler;
        this.iv_idx = iv_idx;
        this.mc_iot_mac = mc_iot_mac;
    }

    public Deal_Fragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.frag_deal, container, false);

        webView = v.findViewById(R.id.wv_act_deal_detail_web);
        ll_act_deal_detail_signature = v.findViewById(R.id.ll_act_deal_detail_signature);
        tv_act_deal_detail_enter = v.findViewById(R.id.tv_act_deal_detail_enter);
        tv_act_deal_detail_complete = v.findViewById(R.id.tv_act_deal_detail_complete);
        ll_act_deal_detail_signature_layout = v.findViewById(R.id.ll_act_deal_detail_signature_layout);
        ll_act_deal_detail_email_layout = v.findViewById(R.id.ll_act_deal_detail_email_layout);
        et_act_deal_detail_email = v.findViewById(R.id.et_act_deal_detail_email);
        tv_act_deal_detail_send = v.findViewById(R.id.tv_act_deal_detail_send);
        progress = v.findViewById(R.id.progress);

        init_Handler();
        init_Listener();
        Set_Contents();
        if (!TextUtils.isEmpty(mc_iot_mac)) mqtt_connect(getContext());
        return v;
    }

    void Set_Contents() {
        url = Common.getInstance().getBaseUrl(fa.userItem.getArrayitem().getAgency().getMbId()) + web_Invoice_URL + iv_idx + web_Url;
        WebSettings settings = webView.getSettings();
        settings.setBuiltInZoomControls(true);
        settings.setSupportZoom(true);
        settings.setUseWideViewPort(true);
        webView.setInitialScale(1);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                view.loadUrl(request.toString());
                return true;
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }
        });

        webView.loadUrl(url);

        SignatureView signatureView = new SignatureView(getContext());
        ll_act_deal_detail_signature.addView(signatureView);

    }

    void init_Handler() {
        hdr = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (msg.what == -1) {
                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();
                } else if (msg.what == 1) {

                    String url = msg.getData().getString("url");
                    if (url.equals("proc_invoice_force_ok")) {
                        progress.setVisibility(View.GONE);
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            Toast.makeText(getContext(), "처리되었습니다.", Toast.LENGTH_LONG).show();
                            getActivity().finish();
                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_LONG).show();
                        }
                    } else if (url.equals("proc_invoice_ok2")) {
                        progress.setVisibility(View.GONE);
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();

                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            Toast.makeText(getContext(), "처리되었습니다.", Toast.LENGTH_LONG).show();

                            fa.isSuccess = Activity.RESULT_OK;
                            ll_act_deal_detail_email_layout.setVisibility(View.VISIBLE);
                            ll_act_deal_detail_signature_layout.setVisibility(View.GONE);
                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_LONG).show();
                        }

                        if (!TextUtils.isEmpty(mc_iot_mac) && (mqttAndroidClient != null || mqttAndroidClient.isConnected())) {
                            mqttAndroidClient.close();
                            mqttAndroidClient.unregisterResources();
                            mqttAndroidClient = null;
                        }
                    } else if (url.equals("proc_word_mail_send")) {
                        progress.setVisibility(View.GONE);
                        JsonElement element = new JsonParser().parse(msg.obj.toString());
                        JsonObject result_item = element.getAsJsonObject();
                        if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                            Toast.makeText(getContext(), "발송되었습니다.", Toast.LENGTH_LONG).show();
                            Common.getInstance().setDirEmpty(getContext(), "/CompcareWorker");
                            getActivity().setResult(Activity.RESULT_OK);
                            getActivity().finish();
                        } else {
                            Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_LONG).show();
                        }
                    }
                }
            }
        };
    }

    private void init_Listener() {
        /** 미결처리*/
        /*tv_act_deal_detail_complete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                dialogBuilder.setTitle("콤프케어 작업자");
                dialogBuilder.setMessage("미결처리 하시겠습니까?");
                dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        progress.setVisibility(View.VISIBLE);
                        HashMap<String, String> data = new HashMap<>();
                        data.put("iv_idx", iv_idx);
                        data.put("mb_id", fa.userItem.getArrayitem().getMbId());
                        new ApiClient(data, "proc_invoice_force_ok", hdr);
                        dialog.dismiss();
                    }
                }).setNegativeButton("취소", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialogBuilder.show();
            }
        });*/

        /** 정식완료*/
        tv_act_deal_detail_enter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                dialogBuilder.setTitle("콤프케어 작업자");
                dialogBuilder.setMessage("완료 하시겠습니까?");
                dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        progress.setVisibility(View.VISIBLE);

                        if (TextUtils.isEmpty(mc_iot_mac)) {
                            getSaveImage("N");
                            return;
                        }

                        String msg = "{'opt' : 10}";
                        JsonParser parser = new JsonParser();
                        Object obj = parser.parse(msg);

//                        if (mqttAndroidClient == null || !mqttAndroidClient.isConnected()) {
//                            Common.getInstance().toastShow(getContext(), "MQTT 서버가 연결되어 있지 않습니다. 잠시 후 다시 시도해주세요.");
//                            mqtt_connect(getContext());
//                            return;
//                        }

                        mqtt_init_success = false;

                        publishMessage("control/" + mc_iot_mac, obj.toString());
                        subscribeTopic("check/" + mc_iot_mac);

                        timer_thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(2000);

                                    if (!mqtt_init_success) {
                                        fa.runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                unSubscribeTopic("check/" + mc_iot_mac);
                                                getSaveImage("N");
                                            }
                                        });
                                    }
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        timer_thread.start();

//                        getSaveImage("Y");
                        dialog.dismiss();
                    }
                }).setNegativeButton("취소", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialogBuilder.show();
            }
        });

        /** 이메일 발송*/
        tv_act_deal_detail_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (et_act_deal_detail_email.getText().toString().equals("")) {
                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                    dialogBuilder.setTitle("콤프케어 작업자");
                    dialogBuilder.setMessage("이메일을 입력하지 않았습니다.\n이메일 전송 없이 완료하시겠습니까?");
                    dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {
                            dialog.dismiss();
                            startActivity(new Intent(getContext(), MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                            getActivity().finish();
                        }
                    }).setNegativeButton("취소", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {
                            Toast.makeText(getContext(), "이메일을 입력하세요.", Toast.LENGTH_LONG).show();
                            dialog.dismiss();
                        }
                    });
                    dialogBuilder.show();
                    return;
                }

                if (Common.getInstance().isValidEmail(et_act_deal_detail_email.getText().toString())) {
                    progress.setVisibility(View.VISIBLE);

                    HashMap<String, String> data = new HashMap<>();
                    data.put("idx", iv_idx);
                    data.put("type", "invoice");
                    data.put("mode", "1");
                    data.put("mail_to", et_act_deal_detail_email.getText().toString());
                    new ApiClient(data, "proc_word_mail_send", hdr);

                } else {
                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                    dialogBuilder.setTitle("콤프케어 작업자");
                    dialogBuilder.setMessage("사용할 수 없는 이메일형식 입니다.\n이메일 전송 없이 완료하시겠습니까?");
                    dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {
                            startActivity(new Intent(getContext(), MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                            getActivity().finish();
                            dialog.dismiss();
                        }
                    }).setNegativeButton("취소", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int i) {
                            Toast.makeText(getContext(), "사용할 수 없는 이메일형식 입니다.", Toast.LENGTH_LONG).show();
                            dialog.dismiss();
                        }
                    });
                    dialogBuilder.show();
                    return;
                }
            }
        });
    }

    void getSaveImage(String type) {

        String saveImgFile = Environment.getExternalStorageState();
        if (saveImgFile.equals(Environment.MEDIA_MOUNTED)) {
            String dirPath = getContext().getExternalFilesDir(saveImgFile).getAbsolutePath() + "/CompcareWorker";

            File file = new File(dirPath);
            if (!file.exists()) {
                file.mkdir();
            }

            Bitmap saveBitmap = getBitmapFromView(ll_act_deal_detail_signature, ll_act_deal_detail_signature.getChildAt(0).getHeight(), ll_act_deal_detail_signature.getChildAt(0).getWidth());
            ll_act_deal_detail_signature.setDrawingCacheEnabled(true);
            FileOutputStream fos;
            try {
                fos = new FileOutputStream(file.toString() + "/CompcareWorker.jpg");
                saveBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
                fos.flush();
                fos.close();

                progress.setVisibility(View.GONE);

                String imageDirPath = getContext().getExternalFilesDir(saveImgFile).getAbsolutePath() + "/CompcareWorker" + "/CompcareWorker.jpg";
                File imageFile = new File(imageDirPath);
                Uri uri = Uri.fromFile(imageFile);

                HashMap<String, String> data = new HashMap<>();
                data.put("iv_idx", iv_idx);
                data.put("mb_id", fa.userItem.getArrayitem().getMbId());
                if (!TextUtils.isEmpty(mc_iot_mac)) data.put("mc_iot_mac", mc_iot_mac);

                String mc_mqtt_service_call_yn = (type.equals("N")) ? "N" : "Y";
                data.put("mc_mqtt_service_call_yn", mc_mqtt_service_call_yn);
                new ApiClient(data, "proc_invoice_ok2", uri, hdr);

                Log.d("보낸다@@@@", data.toString());

            } catch (Exception e) {
                progress.setVisibility(View.GONE);
                Toast.makeText(getContext(), "실패하였습니다.", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        }
    }

    public void mqtt_connect(Context context) {

        String password = "comp1care@#";
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName("compcare");
        mqttConnectOptions.setPassword(password.toCharArray());
        mqttConnectOptions.setConnectionTimeout(10);
        mqttConnectOptions.setCleanSession(true);

        /* Create an MqttAndroidClient object and set a callback interface. */
        mqttAndroidClient = new MqttAndroidClient(context, "tcp://116.125.120.109:1883", MqttClient.generateClientId(), Ack.AUTO_ACK);

        mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                Log.d("연결했다@@@@", "ㅇㅇㅇㅇㅇ");
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {

            }
        });

        mqttAndroidClient.registerResources();
        mqttAndroidClient.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {

            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                JsonParser parser = new JsonParser();
                JsonObject jsonObject = (JsonObject) parser.parse(new String(message.getPayload()));
                MonitoringData monitoringData = new Gson().fromJson(jsonObject, new TypeToken<MonitoringData>() {
                }.getType());

                if (topic.contains("check")) {
                    unSubscribeTopic(topic);

                    if (timer_thread != null) {
                        timer_thread.interrupt();
                        timer_thread = null;
                    }

                    if (monitoringData.getOpt10Cnt() != null && monitoringData.getOpt10Cnt().equals("1")) {
                        getSaveImage("Y");
                        mqtt_init_success = true;
                    } else {
                        getSaveImage("N");
                        mqtt_init_success = false;
                    }
                }
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {

            }
        });
    }

    public void unSubscribeTopic(String topic) {
        if (mqttAndroidClient == null) {
            return;
        }

        IMqttToken unSubToken = mqttAndroidClient.unsubscribe(topic);
        unSubToken.setActionCallback(new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                Log.i("@@@", "unsubscribed succeed");
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                Log.i("@@@", "unsubscribed failed");
            }
        });
    }

    public void subscribeTopic(String topic) {
        if (mqttAndroidClient == null) {
            return;
        }

        mqttAndroidClient.subscribe(topic, 0, null, new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                Log.i("@@@", "subscribed succeed");
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                Log.i("@@@", "subscribed failed");
            }
        });
    }

    public void publishMessage(String topic, String payload) {
        if (mqttAndroidClient == null) {
            return;
        }

        if (!mqttAndroidClient.isConnected()) {
            mqttAndroidClient.connect();
        }

        MqttMessage message = new MqttMessage();
        message.setPayload(payload.getBytes());
        message.setQos(0);
        message.setRetained(false);
        mqttAndroidClient.publish(topic, message, null, new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                Log.i("@@@", "publish succeed! ");
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                Log.i("@@@", "publish failed!");
            }
        });
    }

    Bitmap getBitmapFromView(View view, int totalHeight, int totalWidth) {
        Bitmap bitmap = Bitmap.createBitmap(totalWidth, totalHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Drawable bgDrawble = view.getBackground();

        if (bgDrawble != null) {
            bgDrawble.draw(canvas);
        } else {
            canvas.drawColor(Color.WHITE);
        }

        view.draw(canvas);

        return bitmap;
    }

    class Point {
        float x;
        float y;
        boolean check;

        public Point(float x, float y, boolean check) {
            this.x = x;
            this.y = y;
            this.check = check;
        }
    }

    private class SignatureView extends View {
        ArrayList<Point> points = new ArrayList<>();

        public SignatureView(Context context) {
            super(context);
        }

        @SuppressLint("DrawAllocation")
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            Paint p = new Paint();
            p.setColor(getResources().getColor(R.color.color_text_main));
            p.setStrokeWidth(3F);
            for (int i = 0; i < points.size(); i++) {
                if (!points.get(i).check) continue;
                canvas.drawLine(points.get(i - 1).x, points.get(i - 1).y, points.get(i).x, points.get(i).y, p);
            }

        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            float x = event.getX();
            float y = event.getY();

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    points.add(new Point(x, y, false));
                case MotionEvent.ACTION_MOVE:
                    points.add(new Point(x, y, true));
                    break;
                case MotionEvent.ACTION_UP:
                    break;
            }
            invalidate();
            return true;
        }
    }
}
