package net.yaht.m.iintent2;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    public final static String _PATH_SD_CARD = "/iintent2";
    public final static String _PREFS_FILE = "_iintent2_prefs";

    private static final int ACTIVITY_REQUEST_CODE_CAPTURE = 100;

    private Uri _file_url;

    private int _files_count;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // persistence with settings must be added here;
        // namely shared prefs to hold pics / files generated;

        SharedPreferences prefs = getSharedPreferences(_PREFS_FILE, 0);
        _files_count = prefs.getInt("files_count", 0);

        TextView _status_line = (TextView) findViewById(R.id._txt_status);
        _status_line.setText(new String("files generated: " + _files_count));

    }

    // can we write?
    public boolean isExternalStorageWritable() {

        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state))
            return true;
        return false;

    }

    // can we at least read?
    public boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            return true;
        }
        return false;
    }

    public void btn_take (View v) {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        String _ts = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        _file_url = Uri.fromFile(
                new File (
                            Environment.getExternalStorageDirectory().getAbsolutePath() +
                            _PATH_SD_CARD +
                            "/c_img_" +
                            _ts +
                            ".jpg"
                )
        );
        // set the image file name
        intent.putExtra(MediaStore.EXTRA_OUTPUT, _file_url);

        // or the same code as above, but in separate method
        // _file_url = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

        // start the image capture Intent
        startActivityForResult(intent, ACTIVITY_REQUEST_CODE_CAPTURE);

    }

    public void btn_send(View v) {

        String[] _recipients = {"Hristo Hristov <us3d@abv.bg>"};

        Tools.log2me("=-= MainActivity/btn_send()", "_file_url -> " + _file_url.toString());

        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_EMAIL, _recipients);
        sendIntent.putExtra(Intent.EXTRA_SUBJECT, "A picture ...");
        sendIntent.putExtra(Intent.EXTRA_TEXT, "I'm sending. See it as attachment.");
        sendIntent.setType("text/plain");
        sendIntent.putExtra(Intent.EXTRA_STREAM, _file_url);

        // do we have something to send this message?
        // usually there are more then one apps
        if (sendIntent.resolveActivity(getPackageManager()) != null) {
            startActivity(sendIntent);
        }

    }

    public void btn_gen(View v) {

        boolean _storage = isExternalStorageWritable();

        if (!_storage) return;

        Tools.log2me("=-= MainActivity/btn_get()", "_storage is ok!");

        Bitmap b = Bitmap.createBitmap(640, 480, Bitmap.Config.ARGB_8888);

        Canvas c = new Canvas(b);

        Paint p = new Paint();
        p.setColor(Tools._random_color());
        c.drawRect(0, 0, 639, 479, p);
        p.setColor(Tools._random_color());
        c.drawCircle(320, 230, 100, p);

        String _full_path = Environment.getExternalStorageDirectory().getAbsolutePath() + _PATH_SD_CARD;

        String _ts = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

        try {

            File dir = new File(_full_path);

            if (!dir.exists())
                dir.mkdirs();

            OutputStream fOut;

            File file = new File(_full_path, "g_img_" + _ts + ".png");

            _file_url = Uri.fromFile(file);

            file.createNewFile();
            fOut = new FileOutputStream(file);

            b.compress(Bitmap.CompressFormat.PNG, 100, fOut);

            fOut.flush();
            fOut.close();

        } catch (Exception e) {

        }

        // a little notification;
        Toast.makeText(this, "Generated image stored to: " + _file_url.getPath(), Toast.LENGTH_LONG).show();

        ImageView _img_view = (ImageView) findViewById(R.id._img_view);
        _img_view.setImageDrawable(Drawable.createFromPath(_file_url.getPath()));

        // update files count!
        _files_count++;
        TextView _status_line = (TextView) findViewById(R.id._txt_status);
        _status_line.setText(new String("files generated: " + _files_count));

        // but also update persistent prefs;
        SharedPreferences prefs = getSharedPreferences(_PREFS_FILE, 0);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("files_count", _files_count);
        // and save the result;
        editor.commit();


        // MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == ACTIVITY_REQUEST_CODE_CAPTURE) {

            if (resultCode == RESULT_OK) {

                // a little notification;
                Toast.makeText(this, "Taken image stored to: " + _file_url.getPath(), Toast.LENGTH_LONG).show();

                ImageView _img_view = (ImageView) findViewById(R.id._img_view);
                _img_view.setImageDrawable(Drawable.createFromPath(_file_url.getPath()));

                // update files count!
                _files_count++;
                TextView _status_line = (TextView) findViewById(R.id._txt_status);
                _status_line.setText(new String("files generated: " + _files_count));

                // but also update persistent prefs;
                SharedPreferences prefs = getSharedPreferences(_PREFS_FILE, 0);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putInt("files_count", _files_count);
                // and save the result;
                editor.commit();

            } else if (resultCode == RESULT_CANCELED) {

                // user cancelled the image;

            } else {

                // capture failed, may be advice to used is needed ? :)

            }

        }

    }

}
