package com.example.ghomi.chapter8_4;

import android.Manifest;
import android.content.Intent;
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.EditText;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    EditText editText;
    private int STORAGE_PERMISSIN_CODE = 23;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText =  (EditText)findViewById(R.id.editText);
    }

    public void next (View view){
        Intent intent = new Intent(this, viewActivity.class);
        startActivity(intent);
    }

    public void savePublic(View view){
        ActivityCompat.requestPermissions(this, new String[]
                {Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSIN_CODE);
        String info = editText.getText().toString();
        File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS);
        File myFile = new File(folder, "data1.txt");
        writeData(myFile, info);
    }
    private void writeData(File myFile, String data) {
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(myFile);
            output.write(data.getBytes());
            Toast.makeText(this, "done" + myFile.getAbsolutePath(), Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public void savePrivate(View view){
        String info = editText.getText().toString();
        File folder = getExternalFilesDir("testghomi");
        File myFile = new File(folder, "data2.txt" );
        writeData(myFile, info);
        editText.setText(" ");
    }
}
