package com.algobase.share.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/*
import android.app.Activity;
*/

import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;


import android.content.Intent;
import android.content.DialogInterface;
import android.content.ComponentName;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.LabeledIntent;
import android.content.res.Resources;

import android.net.Uri;

import android.graphics.Color;
import android.graphics.Typeface;

import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;

import android.util.Log;

import androidx.core.content.FileProvider;

import com.algobase.share.app.*;
import com.algobase.share.dialog.*;
import com.algobase.share.compat.*;

import com.algobase.share.compat.Activity;


public class CrashReportActivity extends Activity 
{

   File crash_file;

   ArrayList<Uri> uri_list;

   Intent send_intent;

   ComponentName emailComponentName;

   LinearLayout layout;
   LinearLayout buttons;
   TextView title;
   ScrollView sv;
   TextView tv;
   Button but1;
   Button but2;

   MyDialog dialog;

   void log(String msg) { Log.v("sTracksLog",msg); }

   Uri getFileUri(String path)
   {  
     if (path == null) return null;

     File file = new File(path);

/*
     Uri uri = null;
     if (Build.VERSION.SDK_INT >= 24) 
     { try {
         uri = FileProvider.getUriForFile(this,getPackageName(),file);
       } catch(Exception ex) {}
     }
     else
       uri = Uri.fromFile(file);
*/

     Uri uri = FileProvider.getUriForFile(this,getPackageName(),file);

     return uri;
   }






    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        MyDialog.setStyle(MyDialog.STYLE_HOLO_LIGHT);

        log("CrashReportDialog: onCreate");

        // build main layout

        int screen_margin_bot = 0;
        int screen_margin_top = 0;
   
/*
        if (Build.VERSION.SDK_INT >= 35)
        { Resources res = getResources();
   
          int resId = res.getIdentifier("status_bar_height","dimen","android");
          if (resId > 0) screen_margin_top = res.getDimensionPixelSize(resId);
     
          resId = res.getIdentifier("navigation_bar_height","dimen","android");
          if (resId > 0) screen_margin_bot = res.getDimensionPixelSize(resId);
        }
*/

        layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);

        layout.setPadding(10,screen_margin_top+10,10,screen_margin_bot+10);

        layout.setBackgroundColor(0xff000000);

        title = new TextView(this);
        title.setTextSize(19);
        title.setTextColor(0xffffffff);
        title.setBackgroundColor(0xff777777);
        title.setPadding(10,10,10,10);
        layout.addView(title);
    
        sv =  new ScrollView(this);
   
        tv = new TextView(this);
        tv.setTextSize(16);
        tv.setTextColor(0xffffffff);
        tv.setTypeface(Typeface.MONOSPACE);
        sv.addView(tv);
   
        layout.addView(sv);
        ((LayoutParams)sv.getLayoutParams()).weight = 1.0f;
        ((LayoutParams)sv.getLayoutParams()).topMargin = 10;
        ((LayoutParams)sv.getLayoutParams()).bottomMargin = 15;


        buttons = new LinearLayout(this);

        Button but1 = new Button(this);
        but1.setText("Cancel");
        but1.setTextSize(18);
        but1.setOnClickListener( new OnClickListener() {
             public void onClick(View view) {
                finish();
             }
        });

        buttons.addView(but1);
        ((LayoutParams)but1.getLayoutParams()).weight=1.0f;

        Button but2 = new Button(this);
        but2.setText("Submit");
        but2.setTextSize(18);
        but2.setOnClickListener( new OnClickListener() {
             public void onClick(View view) {
               if (emailComponentName != null) {
                 send_intent.setComponent(emailComponentName);
               }
               startActivity(send_intent);
               finish();
             }
        });

        buttons.addView(but2);
        ((LayoutParams)but2.getLayoutParams()).weight=1.0f;

        layout.addView(buttons);
/*
        buttons.setVisibility(View.GONE);
*/

        setContentView(layout);
        
        adjustLayout(layout,0xff222222);


        String pkg_name = getPackageName();

        int vcode = PackageCompat.getVersionCode(this);

        String version_str;

        if (vcode >= 1000)
          version_str = String.format(Locale.US,"%.3f",0.001f*vcode);
        else
          version_str = String.format(Locale.US,"%.2f",0.01f*vcode);



        Intent intent = getIntent();

        String app_name = intent.getStringExtra(
                                  GlobalExceptionHandler.EXTRA_CRASH_APP_NAME);

        String txt = intent.getStringExtra(
                                  GlobalExceptionHandler.EXTRA_CRASH_TEXT);

        String crash_path = intent.getStringExtra(
                                     GlobalExceptionHandler.EXTRA_CRASH_PATH);

        String log1_path = intent.getStringExtra(
                                     GlobalExceptionHandler.EXTRA_LOG1_PATH);

        String log2_path = intent.getStringExtra(
                                     GlobalExceptionHandler.EXTRA_LOG2_PATH);

        log("crash_path: " + crash_path);
        log("log1_path: " + log1_path);
        log("log2_path: " + log2_path);


        String title_text = app_name + "-" + version_str;
        title_text += "\n";
        title_text +=  pkg_name;
        title_text += "\n";
        title_text +=  "Android: " + "SDK " + Build.VERSION.SDK_INT; 
        title_text += "\n";
        title_text +=  "Device:  " + Build.MODEL;
/*
        title_text += "\n";
        title_text += "crash_path = " + crash_path;
        title_text += "\n";
        title_text += "log1_path = " + log1_path;
        title_text += "\n";
        title_text += "log2_path = " + log2_path;
*/

        String email_text = title_text + "\n\n";

        String html_text = "";


        String lines[]  = txt.split("\n");
  
        for(int i=0; i<lines.length; i++) {

          String s = lines[i].trim();

          email_text += s + "\n\n";

          if (s.indexOf("Exception") != -1) 
            s = "<font color='red'>" + s + "</font>";
          else
            if (s.indexOf("com.algobase") != -1) 
              s = "<font color='yellow'>" + s + "</font>";

          html_text += s + "<br><br>";
       }
 

       title.setText(title_text);
       tv.setText(HtmlCompat.fromHtml(html_text));


       Uri crash_uri = null;
       Uri log1_uri = null;
       Uri log2_uri = null;

       if (new File(crash_path).exists()) crash_uri = getFileUri(crash_path);
       if (new File(log1_path).exists()) log1_uri = getFileUri(log1_path);
       if (new File(log2_path).exists()) log2_uri = getFileUri(log2_path);

       uri_list = new ArrayList<Uri>();

       if (crash_uri != null) uri_list.add(crash_uri);
       if (log1_uri != null) uri_list.add(log1_uri);
       if (log2_uri != null) uri_list.add(log2_uri);


       String addr = "stracks@algobase.com";
       String subj = "Crash Report  " + app_name + " " + version_str;

       //send_intent = new Intent(Intent.ACTION_SEND);
       send_intent = new Intent(Intent.ACTION_SEND_MULTIPLE);

       send_intent.setType("text/plain");
       send_intent.putExtra(Intent.EXTRA_TEXT, email_text);
       send_intent.putExtra(Intent.EXTRA_SUBJECT, subj);

       //send_intent.putExtra(Intent.EXTRA_STREAM, uri);
       send_intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,uri_list);

       String[] addrList = new String[] { addr };
       send_intent.putExtra(Intent.EXTRA_EMAIL,addrList);

       send_intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION |
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION |
                            Intent.FLAG_ACTIVITY_NEW_TASK |
                            Intent.FLAG_ACTIVITY_SINGLE_TOP );

       PackageManager pm = getPackageManager();

       final
       List<ResolveInfo> resolve_list = pm.queryIntentActivities(send_intent,0);
       int resolve_sz = resolve_list.size();

       String title = "sTracks: Internal Error";
       String msg = "Please submit a crash report to " + addr + ".";

       dialog = new MyDialog(this,title);
       dialog.setMessage(msg);

/*
       final RadioGroup grp = new RadioGroup(this);

       int mail_id = 0;

       for(int i=0; i<resolve_sz; i++)
       { ResolveInfo ri = resolve_list.get(i);
         String label = ri.loadLabel(pm).toString();
         String name = ri.activityInfo.name;
         String pname = ri.activityInfo.packageName;

         if (!label.toLowerCase().contains("mail") &&
         //  !label.toLowerCase().contains("whatsapp") &&
             !label.toLowerCase().contains("drive")) continue;

         RadioButton b = dialog.newRadioButton();
         b.setText("  " + label);
         b.setId(1000 + i);
         grp.addView(b);
         if (label.toLowerCase().contains("mail")) {
          emailComponentName = new ComponentName(pname,name);
          mail_id = 1000 + i;
         }
       }

       if (mail_id != 0)
         grp.check(mail_id);
       else
         grp.check(1000);

       LinearLayout layout = new LinearLayout(this);
       layout.setOrientation(LinearLayout.VERTICAL);
       layout.setPadding(0,10,0,20);
       layout.addView(grp);
       dialog.addView(layout);
*/

       dialog.setPositiveButton("Submit", 
          new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface d, int which) {
/*
               int i = grp.getCheckedRadioButtonId()-1000;
               ResolveInfo ri = resolve_list.get(i);
               String name = ri.activityInfo.name;
               String pname = ri.activityInfo.packageName;
               send_intent.setComponent(new ComponentName(pname,name));
*/
               startActivity(send_intent);
               //finish();
             }
       });

       dialog.setNegativeButton("Cancel", 
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface d, int which) {
                    buttons.setVisibility(View.VISIBLE);
                   //finish();
                }
       });

       dialog.show();

    }

}
