package com.idata.ocr.iocr;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;

import com.idata.ocr.OcrResult;
import com.idata.ocr.Predictor;

public class ShowActivity extends AppCompatActivity {
    public static final String KEY_BITMAP = "key_bitmap";

    static public Bitmap mImage = null;
    Predictor predictor = Predictor.getInstance();
    private TextView ocrResult = null;
    private TextView ok_bt = null;
    private ImageView previewView = null;

    private final int RESPONSE_RUN_MODEL_SUCCESSED = 1;
    private final Handler mReceiver = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESPONSE_RUN_MODEL_SUCCESSED:
                    ArrayList<OcrResult> arrayList = (ArrayList<OcrResult>)msg.obj;
                    drawResults(arrayList);

                    if(mWaitingDialog != null)
                        mWaitingDialog.dismiss();

                    break;
                default:
                    break;
            }
        }
    };

    private AlertDialog mWaitingDialog = null;

    @Override
    public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show);

        if(mImage == null)
        {
            finish();
            return;
        }
        previewView = findViewById(R.id.previewView);
        previewView.setImageBitmap(mImage);
        ok_bt = findViewById(R.id.OK);
        ocrResult = findViewById(R.id.ocrResult);

        ok_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.processing_data);
        mWaitingDialog = builder.create();
        mWaitingDialog.setCancelable(false);
        mWaitingDialog.setCanceledOnTouchOutside(false);
        mWaitingDialog.show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                ArrayList<OcrResult> arrayList = predictor.runOcrPredictor(mImage, 0);
                mReceiver.sendMessage(mReceiver.obtainMessage(RESPONSE_RUN_MODEL_SUCCESSED, arrayList));
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void drawResults(ArrayList<OcrResult> results) {
        if(results == null || results.size() == 0) {
            return;
        }
        StringBuffer outputResultSb = new StringBuffer("");
        for (int i = 0; i < results.size(); i++) {
            OcrResult result = results.get(i);
            StringBuilder sb = new StringBuilder("");
            sb.append(result.getLabel());
            sb.append(" ").append(result.getConfidence());
            sb.append("; Points: ");
            for (Point p : result.getPoints()) {
                sb.append("(").append(p.x).append(",").append(p.y).append(") ");
            }
            Log.i("TAG", sb.toString()); // show LOG in Logcat panel
            outputResultSb.append(i + 1).append(": ").append(result.getLabel()).append("\n");
        }
        String outputResult = outputResultSb.toString();
        ocrResult.setText(outputResult);

        Bitmap outputImage = mImage;
        Canvas canvas = new Canvas(outputImage);
        Paint paintFillAlpha = new Paint();
        paintFillAlpha.setStyle(Paint.Style.FILL);
        paintFillAlpha.setColor(Color.parseColor("#3B85F5"));
        paintFillAlpha.setAlpha(50);

        Paint paint = new Paint();
        paint.setColor(Color.parseColor("#3B85F5"));
        paint.setStrokeWidth(5);
        paint.setStyle(Paint.Style.STROKE);

        for (OcrResult result : results) {
            Path path = new Path();
            List<Point> points = result.getPoints();
            path.moveTo(points.get(0).x, points.get(0).y);
            for (int i = points.size() - 1; i >= 0; i--) {
                Point p = points.get(i);
                path.lineTo(p.x, p.y);
            }
            canvas.drawPath(path, paint);
            canvas.drawPath(path, paintFillAlpha);
        }
    }
}
