package com.example.patrice.file01;

import android.content.Context;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

// https://www.journaldev.com/878/java-write-to-file

// https://examples.javacodegeeks.com/core-java/io/java-write-to-file-example/

public class MainActivity extends Activity {

    ArrayList<String> tab = new ArrayList<String>();

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

        tab.add("Item1");
        tab.add("paul");
        tab.add("Remy");
        tab.add("vincent");
        tab.add("pipitron");

        // editText1 File name
        final EditText txtFilename = (EditText) findViewById(R.id.editText1);
        // editText1 String
        final EditText txtString = (EditText) findViewById(R.id.editText2);
        // button1
        final Button btn1 = (Button) findViewById(R.id.button1);

        // Perform action on click
        btn1.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                //create_file();

                //write_arraylist_to_file();

                //read_file_to_arraylist();

                //r();

                SimpleFileWriterExample();
            }
        });

    }

    /*******************************************************/
    /* OK */
    public void create_file()
    {

        try
        {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "mon_fichier.txt";
            File file = new File(path);

            if(!file.exists())
            {
                file.createNewFile();
            }

            String contenu = "Bonjour les petits !";

            FileWriter writer = new FileWriter(file, true); //True = Append to file, false = Overwrite
            writer.write(contenu + "\n");
            writer.close();

            Toast.makeText(MainActivity.this, "File Save!", Toast.LENGTH_LONG).show();

        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(MainActivity.this, "Failed!" + e.getMessage() ,  Toast.LENGTH_LONG).show();
        }

    }

    /*******************************************************/
    /* OK */
    public void write_arraylist_to_file()
    {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "write_fichier.txt";

        FileOutputStream fOut = null;

        try
        {
            fOut = new FileOutputStream(path);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fOut));

        for (int i = 0; i < tab.size(); i++)
        {
            String item = tab.get(i);
            try
            {
                bw.write(item);
                bw.newLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }

        try
        {
            bw.close();
            fOut.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    /*******************************************************/
    /* OK */
    public void read_file_to_arraylist()
    {
        try {

            File sdcard = Environment.getExternalStorageDirectory(); // /mnt/sdcard/

            String path = sdcard + "/write_fichier.txt";
            File file = new File(path);

            BufferedReader br = new BufferedReader(new FileReader(file));
            ArrayList<String> myArr = new ArrayList<String>();

            String line;
            while ((line = br.readLine()) != null)
            {
                myArr.add(line);
            }

            //txt.setText(line); // pour l'affichage

            br.close();

            //File.separator

            //System.Environment.NewLine
            // + "\r\n";
            // System.getProperty("line.separator"))

            // une seule ligne
            /*BufferedReader br = new BufferedReader(new FileReader(file));
            String line;
            line = br.readLine();
            br.close();
            file = null;
            */
/*
            for (int num = 1; num < 11; num++) {
                writer.write("This is line " + num + System.getProperty( "line.separator" ));
            }
  */
        }
        catch (Exception e)
        {
            e.printStackTrace();
            Toast.makeText(MainActivity.this, "Failed! = " + e.getMessage() , Toast.LENGTH_LONG).show();
        }
    }

    /*******************************************************/
    /* OK */
    public void r()
    {
        try
        {
            File sdcard = Environment.getExternalStorageDirectory(); // /mnt/sdcard/
          //  String path = sdcard + "/write_fichier.txt";
          //  BufferedReader inputReader = new BufferedReader(new InputStreamReader( openFileInput( path ) ));


            //FileInputStream fileIn= openFileInput("write_fichier.txt");
            //InputStreamReader inputReader = new InputStreamReader(fileIn);

            String fpath = sdcard + "/write_fichier.txt";

            BufferedReader br = null;
            br = new BufferedReader(new FileReader(fpath));

            String inputString;

            StringBuffer stringBuffer = new StringBuffer();

            while ((inputString = br.readLine()) != null) // inputReader
            {
                stringBuffer.append(inputString + "\n");
            }
            String res = stringBuffer.toString();

            //lblTextViewOne.setText();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    /*******************************************************/

    public void ww()
    {
        File sdcard = Environment.getExternalStorageDirectory();


        File file = new File(sdcard + "/cretin_fichier.txt");
        Writer fileWriter = null;
        BufferedWriter bufferedWriter = null;

        try {

            fileWriter = new FileWriter(file);
            bufferedWriter = new BufferedWriter(fileWriter);
            String line = "";

            for (int k = 0; k < tab.size(); k++)
            {
                line = tab.get(k) + System.getProperty("line.separator");
                bufferedWriter.write(line);
            }

            bufferedWriter.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

    }

    /*******************************************************/

     public void SimpleFileWriterExample()
     {
            String name = "John Doe";
            int age = 44;
            double temp = 26.9;
            FileWriter fw;
            try {
                  fw = new FileWriter(new File("mytextfile.txt"));
                  fw.write(String.format("My name is %s.",name));
                  fw.write(System.lineSeparator()); //new line
                  fw.write(String.format("I am %d years old.",age));
                  fw.write(System.lineSeparator()); //new line
                  fw.write(String.format("Today's temperature is %.2f.",temp));
                  fw.write(System.lineSeparator()); //new line
                  fw.close();
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }




    }

    /*******************************************************/

    public static void writeFile1() throws IOException
    {
        File fout = new File("out.txt");
        FileOutputStream fos = new FileOutputStream(fout);

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

        for (int i = 0; i < 10; i++) {
            bw.write("something");
            bw.newLine();
        }

        bw.close();
    }

    /*******************************************************/

    public static void writeFile2() throws IOException {
        FileWriter fw = new FileWriter("out.txt");

        for (int i = 0; i < 10; i++) {
            fw.write("something");
        }

        fw.close();
    }

    /*******************************************************/

    public static void writeFile3() throws IOException {
        PrintWriter pw = new PrintWriter(new FileWriter("out.txt"));

        for (int i = 0; i < 10; i++) {
            pw.write("something");
        }

        pw.close();
    }

    /*******************************************************/

    public static void writeFile4() throws IOException {
        File fout = new File("out.txt");
        FileOutputStream fos = new FileOutputStream(fout);

        OutputStreamWriter osw = new OutputStreamWriter(fos);

        for (int i = 0; i < 10; i++) {
            osw.write("something");
        }

        osw.close();
    }
/*
    public void PlayWithRawFiles() throws IOException {

        String str = "";

        StringBuffer buf = new StringBuffer();

        InputStream is = this.getResources().openRawResource(R.raw.quiz);

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        if (is != null) {

            while ((str = reader.readLine()) != null) {

                buf.append(str + "\n");

            }

        }
    }
*/

    public void write(Context context, Object nameOfClass) {
        File directory = new File(context.getFilesDir().getAbsolutePath()
                + File.separator + "serlization");
        if (!directory.exists()) {
            directory.mkdirs();
        }

        String filename = "MessgeScreenList.srl";
        ObjectOutput out = null;

        try {
            out = new ObjectOutputStream(new FileOutputStream(directory
                    + File.separator + filename));
            out.writeObject(nameOfClass);
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

/*
    private List<String> getFileListfromSDCard()
    {
        File file;

        List values = new ArrayList();


        String state = Environment.getExternalStorageState();
        List<String> flLst = new ArrayList<String>();
        if (Environment.MEDIA_MOUNTED.equals(state) && file.isDirectory())
        {

            File path;

            List values = new ArrayList();

            File dir = new File("/sdcard/");
            String[] list = dir.list();

            for (String file : list)
            {

                values.add(file);

            }



            //	ArrayAdapter adapter = new ArrayAdapter(this,  R.layout.simple_list_item_1 , android.R.id.text1, values);
            //	    setListAdapter(adapter);


            File[] fileArr = file.listFiles();

            List file_items = new ArrayList();
            List folder_items = new ArrayList();

            List<String> listValues = new ArrayList<String>();


            for (File file : fileArr)
            {
                if (file.isFile())
                {
                    file_items.add(file);
                }
                else if (file.isDirectory())
                {
                    folder_items.add(file);
                }
            }

        }


        //        ArrayAdapter adapter = new ArrayAdapter(this,  android.R.layout.simple_list_item_2, android.R.id.text1, values);
        //        setListAdapter(adapter);

        // ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.activity_main,listValues);



        return flLst;
    }
*/

/*
    void load_image()
    {
        URL imageURL = null;

        try
        {

            imageURL = new URL("http://www.analog-design.net/ALARME/Videos/beach.jpg");
            HttpURLConnection connection = (HttpURLConnection) imageURL.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream inputStream = connection.getInputStream();
            Bitmap bm = BitmapFactory.decodeStream(inputStream);
            image.setImageBitmap(bm);
        }

        catch (IOException e)
        {
            e.printStackTrace();
        }
    }*/
}

// FileWriter fw = new FileWriter(file.getAbsoluteFile());
//  BufferedWriter bw = new BufferedWriter(fw);
//bw.write(fcontent);
//        bw.close();
/*
    StringBuffer output = new StringBuffer();
    String fpath = "/sdcard/"+fname+".txt";

				br = new BufferedReader(new FileReader(fpath));
                        String line = "";
                        while ((line = br.readLine()) != null) {
                        output.append(line +"n");
                        }
*/


/*
class AppendToFileExample { // ABC Hello This is new content  donc on rajoute du texte dans un fichier qui existe , à la suite ...

    private static final String FILENAME = "E:\\test\\filename.txt";

    public void main(String[] args) {

        BufferedWriter bw = null;
        FileWriter fw = null;

        try {

            String data = " This is new content";

            File file = new File(FILENAME);

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            // true = append file
            fw = new FileWriter(file.getAbsoluteFile(), true);
            bw = new BufferedWriter(fw);

            bw.write(data);

            System.out.println("Done");

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                if (bw != null)
                    bw.close();

                if (fw != null)
                    fw.close();

            } catch (IOException ex) {

                ex.printStackTrace();

            }
        }

    }

}
*/


class FileOperations
{
    public FileOperations()
    {

    }

    public Boolean write(String fname, String fcontent)
    {
        try
        {

            String fpath = "/sdcard/"+fname+".txt";

            File file = new File(fpath);

            // If file does not exists, then create it
            if (!file.exists())
            {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(fcontent);
            bw.close();

            Log.d("Suceess","Sucess");
            return true;

        }

        catch (IOException e)
        {
            e.printStackTrace();
            return false;
        }

    }

    public String read(String fname)
    {

        BufferedReader br = null;
        String response = null;

        try {

            StringBuffer output = new StringBuffer();
            String fpath = "/sdcard/"+fname+".txt";

            br = new BufferedReader(new FileReader(fpath));
            String line = "";
            while ((line = br.readLine()) != null) {
                output.append(line +"\n");
            }
            response = output.toString();

        } catch (IOException e) {
            e.printStackTrace();
            return null;

        }
        return response;

    }
}


class MyFile {

    String TAG = "MyFile";
    Context context;
    public MyFile(Context context)
    {
        this.context = context;
    }

    public Boolean writeToSD(String text)
    {
        Boolean write_successful = false;
        File root=null;
        try {
            // check for SDcard
            root = Environment.getExternalStorageDirectory();
            Log.i(TAG,"path.." +root.getAbsolutePath());

            //check sdcard permission
            if (root.canWrite()){
                File fileDir = new File(root.getAbsolutePath());
                fileDir.mkdirs();

                File file= new File(fileDir, "samplefile.txt");
                FileWriter filewriter = new FileWriter(file);
                BufferedWriter out = new BufferedWriter(filewriter);
                out.write(text);
                out.close();
                write_successful = true;
            }
        } catch (IOException e) {
            Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage());
            write_successful = false;
        }
        return write_successful;
    }

    public String readFromSD()
    {
        File sdcard = Environment.getExternalStorageDirectory();
        File file = new File(sdcard,"samplefile.txt");
        StringBuilder text = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }
        }
        catch (IOException e) {
        }
        return text.toString();
    }


}