package gen2wave.rp70biodemo;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;

public class LauncherActivity extends Activity {

    private final int REQUEST_EXTERNAL_STORAGE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        int readPermission = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE);
        int writePermission = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (readPermission == PackageManager.PERMISSION_DENIED || writePermission == PackageManager.PERMISSION_DENIED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_STORAGE);
            } else {
                Intent intent = new Intent(LauncherActivity.this, MainActivity.class);
                startActivity(intent);
                this.finish();
            }
        } else {
            Intent intent = new Intent(LauncherActivity.this, MainActivity.class);
            startActivity(intent);
            this.finish();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grandResults) {

        if (requestCode == REQUEST_EXTERNAL_STORAGE && grandResults.length > 0) {

            int hasReadPermission = ContextCompat.checkSelfPermission(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE);
            int hasWritePermission =
                    ContextCompat.checkSelfPermission(this,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE);

            if (hasReadPermission == PackageManager.PERMISSION_GRANTED
                    && hasWritePermission == PackageManager.PERMISSION_GRANTED) {
                Intent intent = new Intent(LauncherActivity.this, MainActivity.class);
                startActivity(intent);
                this.finish();
            } else {
                Toast.makeText(LauncherActivity.this, "Need a Read/Write Permission.",
                        Toast.LENGTH_LONG).show();
                this.finish();
            }
        }

    }
}
