package edu.brynmawr.ple2;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;

public class MainActivity extends AppCompatActivity {

    public static final int MAT_CAMERA  = 17303;
    public static final int MAT_CAMERA2 = 17304;

    public static final int MAT_EMAIL   = 17305;
    public static final int MAT_LOCATE  = 17306;
    public static final int MAT_LOCATE2  = 17307;
    public static final int MAT_SECOND   = 17308;

    public static final int INTENT_ID_PIC = 17701;
    public static final int INTENT_ID_PIC_SIMPLE = 17702;
    public static final int INTENT_ID_EMAIL = 17703;

    private File photofile;

    public static Bitmap thePicture;
    public static Location currentLocation=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("THISS", "OnCreate Mainact");
        setContentView(R.layout.activity_main);

        Executor exec = new Executor() {
            @Override
            public void execute(@NonNull Runnable command) {
                new Thread(command).start();
            }
        };

        try {
            exec.execute(new Runnable() {
                @Override
                public void run() {
                    DataCities.getInstance(MainActivity.this);
                    Log.i("THISS", "Citites read!");

                }});
            }
        catch (RejectedExecutionException | NullPointerException exception) {
            Log.e("THISS", "Thread problem", exception);
        }

        FragmentManager fragmentManager = this.getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.mainlinearlayout, new FragmentWelcome(), null);
        transaction.addToBackStack(null);
        transaction.commit();
        int tt = fragmentManager.getBackStackEntryCount();
        for(int i = 0; i < tt; ++i) {
            fragmentManager.popBackStack();
        }

        Intent intent = getIntent();
        String action = intent.getAction();

        Log.i("THISS", intent + " " + action);


    }

    public boolean onCreateOptionsMenu(Menu menu){
        Log.i("THISS", "Filling options");
        {
            MenuItem edit_item = menu.add(0, MAT_CAMERA, 1, "C-HD");
            edit_item.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_NEVER);
        }
        {
            MenuItem edit_item = menu.add(0, MAT_CAMERA2, 1, "C-LD");
            edit_item.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_NEVER);
        }
        {
            MenuItem edit_item = menu.add(0, MAT_EMAIL, 1, "EMAIL");
            edit_item.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_NEVER);
        }
        {
            MenuItem edit_item = menu.add(0, MAT_LOCATE, 1, "Loc");
            edit_item.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
        }
        {
            MenuItem edit_item = menu.add(0, MAT_LOCATE2, 1, "L2");
            edit_item.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
        }
        {
            MenuItem edit_item = menu.add(0, MAT_SECOND, 1, "Second");
            edit_item.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_NEVER);
        }


        /*
        MenuItem delete_item = menu.add(0, 17235, 2, "Geoff");
        delete_item.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_NEVER);
        MenuItem geoff2 = menu.add(1, 17236, 3, "Geoff2");
        geoff2.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
*/
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        Log.i("THISS", "Clicked on menu item " + id);

        if (id==MAT_CAMERA) {
            doPhotoIntent();
            return true;
        }
        if (id==MAT_CAMERA2) {
            doPhotoIntentSimple();
            return true;
        }

        if (id==MAT_SECOND) {
            Intent intent = new Intent(MainActivity.this,SecondActivity.class);
            intent.putExtra("username", "UserName");
            intent.putExtra("password", "UserPassword");
            startActivity(intent);
        }

        if (id == MAT_EMAIL) {
            if (thePicture==null)
                doEmail2();
            else
                doEmail();
            //Toast.makeText(this, "BY LAUNCHER", Toast.LENGTH_LONG).show();
            /*
            FragmentManager fragmentManager = this.getSupportFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(MAIN_ACTIVITY_ID, new FragmentLauncher(id), null);
            transaction.addToBackStack(null);
            transaction.commit();
             */
            return true;
        }
        if (id == MAT_LOCATE) {
            Toast.makeText(this, "Location", Toast.LENGTH_LONG).show();
            FragmentManager fragmentManager = this.getSupportFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.mainlinearlayout, new FragmentLocation(), null);
            transaction.addToBackStack(null);
            transaction.commit();
            return true;
        }
        if (id == MAT_LOCATE2) {
            Toast.makeText(this, "Location", Toast.LENGTH_LONG).show();
            FragmentManager fragmentManager = this.getSupportFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.mainlinearlayout, new FragmentDistances(), null);
            transaction.addToBackStack(null);
            transaction.commit();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void onBackPressed() {
        FragmentManager fragmentManager = this.getSupportFragmentManager();
        int tt = fragmentManager.getBackStackEntryCount();
        Log.i("THISs", "Back stack " + tt);
        if (tt>1)
            super.onBackPressed();
    }

    private void doEmail() {
        try
        {
            PackageInfo pinfo = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
            long versionNumber = pinfo.versionCode;
            String versionName = pinfo.versionName;
            String s="";
            s += "\nAndroid API " + android.os.Build.VERSION.SDK_INT;
            s += "\n Model (and Product): " + android.os.Build.MODEL + " ("+ android.os.Build.PRODUCT + ")\n";
            s += "\n App Id " + versionNumber + " " + versionName;
            s += "\n\nPlease list your questions or comments below including your full name and email address.\n\n";
            if (currentLocation!=null)
                s += String.format("Your current location: %6.2f, %6.2f", currentLocation.getLongitude(), currentLocation.getLatitude());
            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("application/jgz");
            i.putExtra(Intent.EXTRA_SUBJECT, "The photo I just took");
            i.putExtra(Intent.EXTRA_TEXT   , s);
            File ff = createFileContainingImage();
            if (ff!=null) {
                Log.i("THISS", "PHOTO URI: " + ff.length() + " " + ff.toURI());
                Uri imageUri = FileProvider.getUriForFile(this,
                        "edu.brynmawr.ple2.fileprovider",
                        ff);
                i.putExtra(Intent.EXTRA_STREAM, imageUri);
            }
            this.startActivityForResult(Intent.createChooser(i, "Send mail..."), INTENT_ID_EMAIL);
        }
        catch (Exception ee)
        {
            ee.printStackTrace();
        }

    }

    private void doEmail2() {
        try
        {
            PackageInfo pinfo = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
            long versionNumber = pinfo.versionCode;
            String versionName = pinfo.versionName;
            String s="";
            s += "\nAndroid API " + android.os.Build.VERSION.SDK_INT;
            s += "\n Model (and Product): " + android.os.Build.MODEL + " ("+ android.os.Build.PRODUCT + ")\n";
            s += "\n App Id " + versionNumber + " " + versionName;
            s += "\n\nPlease list your questions or comments below including your full name and email address.\n\n";
            if (currentLocation!=null)
                s += String.format("Your current location: %6.2f, %6.2f", currentLocation.getLongitude(), currentLocation.getLatitude());
            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("text/plain");
            i.putExtra(Intent.EXTRA_SUBJECT, "Some Data");
            i.putExtra(Intent.EXTRA_TEXT   , s);
            File ff = createFileContainingText();
            if (ff!=null) {
                Log.i("THISS", "URI: " + ff.length() + " " + ff.toURI());
                Uri uri = FileProvider.getUriForFile(this,
                        "edu.brynmawr.ple2.fileprovider",
                        ff);
                i.putExtra(Intent.EXTRA_STREAM, uri);
            }
            this.startActivityForResult(Intent.createChooser(i, "Send mail..."), INTENT_ID_EMAIL);
        }
        catch (Exception ee)
        {
            ee.printStackTrace();
        }

    }

    private File createFileContainingText() throws IOException {
        String timeStamp = new SimpleDateFormat("HHmmss").format(new Date());
        String fileName = timeStamp;
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File ffile = File.createTempFile(
                fileName,  /* prefix */
                ".qqq",         /* suffix */
                storageDir      /* directory */
        );
        String s="";
        try {
            PackageInfo pinfo = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
            long versionNumber = pinfo.versionCode;
            String versionName = pinfo.versionName;
            s += "\nAndroid API " + android.os.Build.VERSION.SDK_INT;
            s += "\n Model (and Product): " + android.os.Build.MODEL + " (" + android.os.Build.PRODUCT + ")\n";
            s += "\n App Id " + versionNumber + " " + versionName;
            s += "\n\nPlease list your questions or comments below including your full name and email address.\n\n";
            if (currentLocation != null)
                s += String.format("Your current location: %6.2f, %6.2f", currentLocation.getLongitude(), currentLocation.getLatitude());
        } catch (Exception ee) {
            Log.e("THISS", ee.toString(), ee);
        }
        Log.i("THISS", "FFFILE " + ffile);
        try {
            FileOutputStream out = new FileOutputStream(ffile);
            PrintStream buff = new PrintStream(out);
            buff.println("hello");
            buff.println(s);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ffile;

    }
    private File createFileContainingImage() throws IOException {
        // Create a file
        if (thePicture==null)
            return null;
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jgz",         /* suffix */
                storageDir      /* directory */
        );
        Log.i("THISS", "FFFILE " + image);
        try {
            FileOutputStream out = new FileOutputStream(image);
            thePicture.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return image;
    }

    private File createFileForImage() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
        Log.i("THISS", "FFFILE " + image);
        return image;
    }

    public void doPhotoIntentSimple() {
        Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(camera_intent, INTENT_ID_PIC_SIMPLE);
    }

    public void doPhotoIntent() {
        Log.e("THISSScF", "taking picture");
        Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
        getIntent.setType("image/*");

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        try {
            photofile = createFileForImage();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        Log.i("THISS", "PPPPP7   " + photofile);
        if (photofile != null) {
            Uri imageUri = FileProvider.getUriForFile(this,
                    "edu.brynmawr.ple2.fileprovider",
                    photofile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            //Bundle extras = new Bundle();
            //extras.putString("FILE", photofile.toString());
            //takePictureIntent.putExtras(extras); //notice the different method
            Log.i("THISS", "CALL INTEnt " + takePictureIntent);
            startActivityForResult(takePictureIntent, INTENT_ID_PIC);
        }
    }

    private void photoProblem() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Problem getting picture")
                .setMessage("Problem getting picture, please try again.")
                .setNeutralButton("OK",
                        new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int which)
                            {
                                dialog.dismiss();
                            }
                        })
                .show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent )
    {
        super.onActivityResult(requestCode, resultCode, intent);
        Log.i("THISS", "Receive intent " + intent);
        if (requestCode == INTENT_ID_EMAIL) {
            Log.i("THISS", "EMail intent completed ... result is unknown and unknowable per spec");
            return;
        }
        if (requestCode==INTENT_ID_PIC_SIMPLE) {
            if (Activity.RESULT_OK != resultCode) {
                photoProblem();
                return;
            }

            Bundle extras = intent.getExtras();
            if (extras != null) {
                Bitmap xx = (Bitmap) extras.get("data");
                Log.i("THISS", "Bitmap " + xx.getByteCount() + "  " + xx.getWidth() + " " + xx.getHeight());
                thePicture = xx;
            }
            switchToPhotoFragment();
        }
        if (requestCode==INTENT_ID_PIC)
        {
            if (Activity.RESULT_OK != resultCode) {
                photoProblem();
                return;
            }
            try
            {
                Bitmap bitmap = BitmapFactory.decodeFile(photofile.toString());
                thePicture=bitmap;
                photofile.delete();
                /*
                * Could go through the FileProvider thing again, but since I own the file ...
                Bundle extras = intent.getExtras();
                Uri imageUri = FileProvider.getUriForFile(this,
                        "edu.brynmawr.ple2.fileprovider",
                        photofile);
                if (imageUri!=null) {
                    BitmapFactory.Options o2 = new BitmapFactory.Options();
                    thePicture = BitmapFactory.decodeStream(this.getContentResolver().openInputStream(imageUri), null, o2);
                    photofile.delete();
                } else {
                    //Bundle extras = intent.getExtras();
                    if (extras != null) {
                        Bitmap xx = (Bitmap) extras.get("data");
                        Log.i("THISS", "Bitmap " + xx.getByteCount() + "  " + xx.getWidth() + " " + xx.getHeight());
                        thePicture = xx;
                    } else {
                        // really should never be here!!!
                    }
                }

                 */
                switchToPhotoFragment();
            }
            catch (Exception ee)
            {
                ee.printStackTrace();
                photoProblem();
            }
        }
        else
        {
            Log.e("THISS", "UNKNOWN result " + requestCode + " " + resultCode + " " + intent);
            // get here when user cancels out of message sending
        }
    }

    private void switchToPhotoFragment() {
        FragmentManager fragmentManager = this.getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.mainlinearlayout, new FragmentPhoto(), null);
        transaction.addToBackStack(null);
        transaction.commit();
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i("THISS", "onStop Main");
    }
    @Override
    public void onPause() {
        super.onPause();
        Log.i("THISS", "onPause Main");
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("THISS", "onDestroy Main");
    }

}