/**
 * Copyright (C) 2016 mplacona.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package uk.co.placona.selfie;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;


/**
 * Class to simplify the taking screenshots of your apps
 */
public final class Selfie {

    // Storage Permissions variables
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private static final String TAG = "Selfie";
    private static SelfieInstance mInstance;

    public static void initialize(){
        if (mInstance == null) {
            mInstance = new SelfieInstance
                    .SelfieBuilder()
                    .format("yyyy-MM-dd_hh:mm:ss")
                    .path(Environment.getExternalStorageDirectory().toString())
                    .quality(100)
                    .build();
        }
    }

    private static void verifyStoragePermissions(Activity activity) {
        // Check if we have read or write permission
        int writePermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (writePermission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode,
//                                           String permissions[], int[] grantResults) {
//        switch (requestCode) {
//            case REQUEST_EXTERNAL_STORAGE: {
//                // If request is cancelled, the result arrays are empty.
//                if (grantResults.length > 0
//                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//
//                    // permission was granted, yay!
//                    takeScreenShot(mActivity);
//
//                } else {
//
//                    // permission denied, boo! Disable the
//                    // functionality that depends on this permission.
//                }
//                return;
//            }
//
//            // other 'case' lines to check for other
//            // permissions this app might request
//        }
//    }

    /**
     * Create a snapshot
     *
     * @param activity Activity used by Selfie.
     */
    public static void snap(Activity activity) {
        verifyStoragePermissions(activity);
        takeScreenShot(activity);
    }

    private static void takeScreenShot(Activity activity) {
        Date now = new Date();
        android.text.format.DateFormat.format(mInstance.getFormat(), now);

        try {
            // image naming and path  to include sd card  appending name you choose for file
            String mPath = mInstance.getPath() + "/" + now + ".jpg";

            // create bitmap screen capture
            View v1 = activity.getWindow().getDecorView().getRootView();
            v1.setDrawingCacheEnabled(true);
            Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
            v1.setDrawingCacheEnabled(false);

            File imageFile = new File(mPath);

            FileOutputStream outputStream = new FileOutputStream(imageFile);
            int quality = mInstance.getQuality();
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
            outputStream.flush();
            outputStream.close();

            Log.d(TAG, "snap: " + mPath);


        } catch (Throwable e) {
            // Several error may come out with file handling or OOM
            e.printStackTrace();
        }
    }
}

@@ -824,16 +824,65 @@
 Compat;%0A
+import android.support.v4.content.ContextCompat;%0A
 import a
@@ -923,16 +923,45 @@
 ew.View;
+%0Aimport android.widget.Toast;
 %0A%0Aimport
@@ -1205,136 +1205,21 @@
 EST_
-EXTERNAL_STORAGE = 1;%0A    private static String%5B%5D PERMISSIONS_STORAGE = %7B%0A            Manifest.permission.WRITE_EXTERNAL
+WRITE
 _STORAGE
 %0A   
@@ -1214,22 +1214,22 @@
 _STORAGE
-%0A    %7D
+ = 112
 ;%0A%0A    p
@@ -1687,144 +1687,169 @@
     
-private static void verifyStoragePermissions(Activity activity) %7B%0A        // Check if we have read or write permission%0A        int write
+/**%0A     * Create a snapshot%0A     *%0A     * @param activity Activity used by Selfie.%0A     */%0A    public static void snap(Activity activity) %7B%0A%0A        boolean has
 Perm
@@ -1857,24 +1857,24 @@
 ssion = 
-Activity
+(Context
 Compat.c
@@ -1901,16 +1901,32 @@
 ctivity,
+%0A               
  Manifes
@@ -1965,40 +1965,10 @@
 AGE)
-;%0A%0A        if (writePermission !
+ =
 = Pa
@@ -1999,18 +1999,17 @@
 GRANTED)
- %7B
+;
 %0A       
@@ -2013,58 +2013,29 @@
     
-    // We don't have permission so prompt the user
+if (!hasPermission) %7B
 %0A   
@@ -2077,37 +2077,16 @@
 issions(
-%0A                    
 activity
@@ -2111,682 +2111,118 @@
     
-PERMISSIONS_STORAGE,%0A                    REQUEST_EXTERNAL_STORAGE%0A            );%0A        %7D%0A    %7D%0A%0A//    @Override%0A//    public void onRequestPermissionsResult(int requestCode,%0A//                                           String permissions%5B%5D, int%5B%5D grantResults) %7B%0A//        switch (requestCode) %7B%0A//            case REQUEST_EXTERNAL_STORAGE: %7B%0A//                // If request is cancelled, the result arrays are empty.%0A//                if (grantResults.length %3E 0%0A//                        && grantResults%5B0%5D == PackageManager.PERMISSION_GRANTED) %7B%0A//%0A//                    // permission was granted, yay!%0A//                    takeScreenShot(mActivity);%0A//%0A//    
+new String%5B%5D%7BManifest.permission.WRITE_EXTERNAL_STORAGE%7D,%0A                    REQUEST_WRITE_STORAGE);%0A
         
     
@@ -2221,27 +2221,16 @@
     
-    %7D 
+%7D
 else %7B%0A
-//%0A// 
     
@@ -2241,516 +2241,8 @@
     
-       // permission denied, boo! Disable the%0A//                    // functionality that depends on this permission.%0A//                %7D%0A//                return;%0A//            %7D%0A//%0A//            // other 'case' lines to check for other%0A//            // permissions this app might request%0A//        %7D%0A//    %7D%0A%0A    /**%0A     * Create a snapshot%0A     *%0A     * @param activity Activity used by Selfie.%0A     */%0A    public static void snap(Activity activity) %7B%0A        verifyStoragePermissions(activity);%0A        
 take
@@ -2262,16 +2262,26 @@
 tivity);
+%0A        %7D
 %0A    %7D%0A%0A

Change authentication dance