package com.example.patrice.http01;

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.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

// http://wptrafficanalyzer.in/blog/deleting-selected-items-from-listview-in-android/

//http://www.androidinterview.com/android-custom-listview-with-checkbox-example/
//http://www.dev2qa.com/android-listview-example/

public class listview02 extends ListActivity
{
    ArrayList<String> list = new ArrayList<String>();
    ArrayAdapter<String> adapter;

    Button btn;
    Button btnDel;

    @Override
    protected void onResume()
    {
        super.onResume();
        refresh();
    }

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

        btn = (Button) findViewById(R.id.btnAdd);
        btnDel = (Button) findViewById(R.id.btnDel);

        load_file_to_list();

        /** Defining the ArrayAdapter to set items to ListView */
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, list);

        /** Defining a click event listener for the button "Add" */
        OnClickListener listener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText edit = (EditText) findViewById(R.id.txtItem);

                //if(list.indexOf(edit) > -1)
                if(list.contains(edit.getText().toString() ) )
                {
                    //item is existing in the list
                    Toast.makeText(getApplicationContext(), "Exists in list !.", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    // not existing
                    list.add(edit.getText().toString());
                    btnDel.setEnabled(true);
                    edit.setText("");
                    adapter.notifyDataSetChanged();
                }
            }
        };

        /** Defining a click event listener for the button "Delete" */
        OnClickListener listenerDel = new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(listview02.this);
                alertDialog.setTitle("Confirm Delete...");
                alertDialog.setMessage("Are you sure you want delete this?");
                alertDialog.setIcon(R.drawable.delete);

                alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog,int which)
                    {
                        //Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();

                        /** Getting the checked items from the listview */
                        SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
                        int itemCount = getListView().getCount();

                        for(int i=itemCount-1; i >= 0; i--)
                        {
                            if(checkedItemPositions.get(i))
                            {
                                adapter.remove(list.get(i));
                            }
                        }
                        refresh();
                        checkedItemPositions.clear();
                        adapter.notifyDataSetChanged();
                    }
                });

                alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int which)
                    {
                            //Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
                            FileOutputStream fOut = null;
                            BufferedWriter bw = null;
                            String filename = Environment.getExternalStorageDirectory() + "/" + "myFile.txt";

                            try
                            {
                                fOut = new FileOutputStream(filename);
                                bw = new BufferedWriter(new OutputStreamWriter(fOut));

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

                                }

                            }
                            catch (FileNotFoundException e)
                            {
                                e.printStackTrace();
                            }

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

                            dialog.cancel();
                    }
                });

                // Showing Alert Message
                alertDialog.show();

            }
        };

        /** Setting the event listener for the add button */
        btn.setOnClickListener(listener);

        /** Setting the event listener for the delete button */
        btnDel.setOnClickListener(listenerDel);

        /** Setting the adapter to the ListView */
        setListAdapter(adapter);
    }


    public void refresh()
    {
        if(list.size() == 0)
        {
            Toast.makeText(getApplicationContext(), "Vide", Toast.LENGTH_SHORT).show();
            btnDel.setEnabled(false);
        }
    }

    @Override
    public void onBackPressed()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        builder.setMessage("Do you want to Exit ?");
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                save_list_to_file();
                finish();
            }
        });

        builder.setNegativeButton("No", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.cancel();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }


    public void load_file_to_list()
    {
        try
        {
            String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myfile.txt";
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "Cp1252"), 100);

            String line;
            ArrayList<String> lines = new ArrayList<String>();
            while ((line = br.readLine()) != null) {
                list.add(line);
            }

            br.close();

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    public void save_list_to_file()
    {
        FileOutputStream fOut = null;
        BufferedWriter bw = null;
        String filename = Environment.getExternalStorageDirectory() + "/" + "myFile.txt";

        try
        {
            fOut = new FileOutputStream(filename);
            bw = new BufferedWriter(new OutputStreamWriter(fOut));

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

            }
        }

        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }

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


    }

/*
    public void read(View view)
    {
        try
        {
            FileInputStream fileInputStream= openFileInput("myText.txt");
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuffer stringBuffer = new StringBuffer();
            String lines;
            while ((lines=bufferedReader.readLine())!=null) {
                stringBuffer.append(lines+"\n");
            }
            textView.setText(stringBuffer.toString());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
*/
/*
    public void write(View view)
    {
        String Mytextmessage  = editText.getText().toString();
        try
        {
            FileOutputStream fileOutputStream = openFileOutput("myText.txt",MODE_PRIVATE);
            fileOutputStream.write(Mytextmessage.getBytes());
            fileOutputStream.close();
            Toast.makeText(getApplicationContext(),"Text Saved",Toast.LENGTH_LONG).show();
            editText.setText("");
        }

        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }

        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
  */
}
/*
    String name = name_et.getText().toString();
    String extSdcard = Environment.getExternalStorageDirectory().toString();
    file = new File(extSdcard, name);
    file.mkdir();
*/


/*
    AlertDialog.Builder dlgAlert2 = new AlertDialog.Builder(this);
            dlgAlert2.SetMessage("Status update failed.");
                    dlgAlert2.SetTitle("Event Detail Error");
                    dlgAlert2.SetPositiveButton("OK", (sender2, e) =>
                    {
                    dlgAlert2.Dispose();
                    CloseActivity();
                    });
                    dlgAlert2.Show();
                    }
                    }

private void CloseActivity()
        {
        this.Finish();
        }
*/