package com.performics;

import android.annotation.SuppressLint;
import android.content.Intent;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ActivityEventListener;
import java.lang.String;
import java.lang.Boolean;
import java.lang.Integer;
import androidx.annotation.NonNull;
import android.util.Log;

import com.facebook.react.bridge.Promise;

import android.app.ProgressDialog;
import android.widget.Toast;

import android.app.Activity;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.json.JSONObject;
import org.json.JSONException;
import android.content.BroadcastReceiver;
// import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import android.graphics.Paint;
import java.io.ByteArrayOutputStream;
import android.net.Uri;
import java.lang.*;
import java.io.FileOutputStream;
import java.io.File;
import android.text.TextPaint;
import android.text.Layout;
import android.text.StaticLayout;

import java.lang.Thread;
import android.graphics.Typeface;

public class ImageMarkTextModule extends ReactContextBaseJavaModule implements ActivityEventListener{
    public static final String REACT_CLASS = "ImageMarkText";
    private static ReactApplicationContext reactContext;
    private ProgressDialog dialog = null;
    final Boolean[] isSdkInitialized = new Boolean[1];
    String returntempSessionId = "";
    private Promise iRCameraPromise=null;
    BroadcastReceiver listenForBroadCast;
    
    
    private int RESULT_OK =-1;
  
    public ImageMarkTextModule(@NonNull ReactApplicationContext reactContext) {
      super(reactContext);
      this.reactContext = reactContext;
      reactContext.addActivityEventListener(this); //Register this native module as Activity result listener
      Log.d("ImageMarkTextModule", "init module");
    }

    @Override
    public void onNewIntent(@NonNull Intent intent) {

    }

    @Override
    public void onActivityResult(@NonNull Activity activity, int requestCode, int resultCode, Intent data) {
      // Here is your Activity result :)
      Log.i("ImageMarkTextModule", "onActivityResult: " + resultCode);
    }


    
    @NonNull
    @Override
    public String getName() {
      return REACT_CLASS;
    }

    @SuppressLint("SimpleDateFormat")
    @ReactMethod
    public void NativeImageMarkText(String TextInfo,String ImgInfo,final Promise promise) {
      // starting the infilect login
      Calendar calendar = Calendar.getInstance();
      SimpleDateFormat format = new SimpleDateFormat("MM/DD/yyyy 'at' h:mm:ss a");
      // Log.d("markText", "Mark Text Start "+format.format(calendar.getTime()));
      Log.d("markText", "markText Text:"+TextInfo);
      Log.d("markText", "markText ImgURL:"+ImgInfo);
      Boolean isSdkLoggedIn=false;

      try{
        JSONObject TextObj = new JSONObject(TextInfo);
        JSONObject ImgObj = new JSONObject(ImgInfo);
        class MarkTextApp {
          public String getImageUri(Bitmap inImage) {
            try{
              Calendar calendar1 = Calendar.getInstance();
              SimpleDateFormat format1 = new SimpleDateFormat("MM/DD/yyyy 'at' h:mm:ss a");   
              File tempFile = File.createTempFile("testtempimg", ".jpg");
              ByteArrayOutputStream bytes =new ByteArrayOutputStream();
              inImage.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
              byte bitmapData[] = bytes.toByteArray();
              FileOutputStream fileOutPut = new FileOutputStream(tempFile);
              fileOutPut.write(bitmapData);
              fileOutPut.flush();
              fileOutPut.close();
              
              Uri uri=Uri.fromFile(tempFile);
              return uri.toString();
            }catch(Exception e) {
              Log.d("markText", "Error while generating local file : "+e.getMessage());
              
              return "";
            }
          }
          public void CanvasMarkText() {

            Thread thread = new Thread() {
              @Override
              public void run() {
                try {
                  Calendar calendar1 = Calendar.getInstance();
                  SimpleDateFormat format1 = new SimpleDateFormat("MM/DD/yyyy 'at' h:mm:ss a");
                  

                  int mColorBackground=Color.parseColor("#ffffffff");
                  int mTextColor=Color.parseColor("red");	
                  
                  String Text=TextObj.getString("text");
                  String BottomText=TextObj.getString("BottomText");
                  JSONObject TextStyle=TextObj.getJSONObject("textStyle");
                  String TopTextfontSize=TextStyle.getString("TopTextfontSize");
                  String TopText_x=TextStyle.getString("TopText_x");
                  String TopText_y=TextStyle.getString("TopText_y");
                  Float TopTextfontSize_F = Float.parseFloat(TopTextfontSize);
                  Float TopText_xF = Float.parseFloat(TopText_x);
                  Float TopText_yF = Float.parseFloat(TopText_y);
  
                  String BottomTextfontSize=TextStyle.getString("BottomTextfontSize");
                  String BottomText_x=TextStyle.getString("BottomText_x");
                  String BottomText_y=TextStyle.getString("BottomText_y");
                  int BottomTextfontSize_F = Integer.parseInt(BottomTextfontSize);
                  int BottomText_xF = Integer.parseInt(BottomText_x);
                  int BottomText_yF = Integer.parseInt(BottomText_y);
  
                  String src=ImgObj.getString("src");
                  String height=ImgObj.getString("height");
                  String ExtendedHeight=ImgObj.getString("ExtendedHeight");
                  String width=ImgObj.getString("width");
  
                  
                  BitmapFactory.Options opt = new BitmapFactory.Options();
                  opt.inMutable = true;
                  Bitmap bMap = BitmapFactory.decodeFile(src,opt); 
                  
                  Bitmap bg_bMap=Bitmap.createBitmap(Integer.parseInt(width), Integer.parseInt(ExtendedHeight), Bitmap.Config.ARGB_8888);
                  // bMap= bMap.copy(Bitmap.Config.ARGB_8888, true);
                  Canvas  mCanvas = new Canvas(bg_bMap);
                  mCanvas.drawColor(mColorBackground);
  
                  
                  Paint paint = new Paint(); 
                  mCanvas.drawBitmap(bMap,0f,0f,paint);
                  
                  paint.setColor(mTextColor);
                  //Typeface tf =Typeface.createFromAsset(reactContext.getAssets(),"fonts/Roboto-Regular.ttf");
                  paint.setTypeface(Typeface.DEFAULT);
                  paint.setTextSize(TopTextfontSize_F); 
                  mCanvas.drawText(Text, TopText_xF, TopText_yF, paint); 
                  
                  // paint.setTextSize(BottomTextfontSize_F); 
                  // mCanvas.drawText(BottomText, BottomText_xF, BottomText_yF, paint); 
                  
                  // Drawable d = new BitmapDrawable(bMap); 
                  // d.setBounds(10, 10, 0, 0); 
                  // d.draw(canvas);
  
                  // String BottomText = "This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.";
  
                  TextPaint myTextPaint = new TextPaint();
                  myTextPaint.setTextSize(BottomTextfontSize_F);
                  myTextPaint.setColor(mTextColor);
                  myTextPaint.setTypeface(Typeface.DEFAULT);
  
                  
                  int txt_width = Integer.parseInt(width);
                  Layout.Alignment alignment = Layout.Alignment.ALIGN_NORMAL;
                  float spacingMultiplier = 1;
                  float spacingAddition = 0;
                  boolean includePadding = false;
  
                  StaticLayout myStaticLayout = new StaticLayout(BottomText, myTextPaint, txt_width, alignment, spacingMultiplier, spacingAddition, includePadding);
                  mCanvas.save();
                  float txt_gheight = myStaticLayout.getHeight();
                  mCanvas.translate(BottomText_xF, BottomText_yF);
  
                  //draws static layout on canvas
                  myStaticLayout.draw(mCanvas);
                  mCanvas.restore();
  
                  

                  String url=getImageUri(bg_bMap);
                  promise.resolve(url);
                  
                } catch (Exception e) {
                  e.printStackTrace();
                  promise.resolve(false);
                }
              }
            };
            
            thread.start();
            
          }
      
        }
      
      
        MarkTextApp mImgObj= new MarkTextApp();
        mImgObj.CanvasMarkText();
      
      }
      catch(JSONException je) {
        Log.d("markText", "markText JSON Parse Error");
        Toast.makeText(reactContext,"markText failed (JSON Parse Error): "+je.getMessage(), Toast.LENGTH_SHORT).show();
        je.printStackTrace();
        promise.resolve(null);
      }
      catch(Exception e){
        Log.d("markText", "Error : "+e.getMessage());
        e.printStackTrace();
        promise.resolve(false);
      }
      
    }
   
  }