package com.zatackcoder.storefile;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback{

    TextView dataAndInfoTV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dataAndInfoTV = (TextView)findViewById(R.id.data_and_info);

        Button writeB = (Button)findViewById(R.id.writeB);
        Button readB = (Button)findViewById(R.id.readB);

        writeB.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                if(isExternalStorageWritable()){
                    Toast.makeText(getApplicationContext(), "External Storage Writable", Toast.LENGTH_LONG).show();
                    File file = new File(Environment.getExternalStorageDirectory(),"storagefile");
                    if(!file.exists()){
                        if(file.mkdir()){
                            Toast.makeText(getApplicationContext(), "Directory created", Toast.LENGTH_LONG).show();
                        }

                    } else {
                        Toast.makeText(getApplicationContext(), "Directory already available", Toast.LENGTH_LONG).show();
                        dataAndInfoTV.setText(file.getAbsolutePath());
                    }

                    File newfile = new File(file.getAbsolutePath()+"/testfile.txt");
                    try {
                        if(!newfile.exists()){
                            newfile.createNewFile();
                        }
                        FileOutputStream outputStream = new FileOutputStream(newfile);
                        outputStream.write("This is file content".getBytes());
                        outputStream.close();
                        Toast.makeText(getApplicationContext(), "File created", Toast.LENGTH_LONG).show();
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Error while creating File", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "External Storage Not Writable", Toast.LENGTH_LONG).show();
                }
            }
        });

        readB.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/storagefile/testfile.txt");
                if(file != null && file.exists()){

                    try {
                        FileInputStream fis = new FileInputStream(file);
                        String str = "";
                        int data;
                        while((data = fis.read()) != -1){
                            str += (char)data;
                        }
                        dataAndInfoTV.setText(str);
                    } catch (FileNotFoundException e) {
                        Toast.makeText(getApplicationContext(), "File not found", Toast.LENGTH_LONG).show();
                    } catch (IOException e) {
                        Toast.makeText(getApplicationContext(), "Error while reading File", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "File does not exists", Toast.LENGTH_LONG).show();
                }
            }
        });

        //Getting permission for Marshmallow or higher version at runtime
        getExternalStorageWritePermission();

    }


    /* Checks if external storage is available for read and write */
    private boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    private void getExternalStorageWritePermission(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                // Should we show an explanation?
                if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                } else {
                    //Requesting permission.
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                }

            }
        }
    }

    @Override //Override from ActivityCompat.OnRequestPermissionsResultCallback Interface
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission granted
                }
                return;
            }
        }
    }
}
