package com.example.patrice.mysql01;


import java.io.BufferedReader;
import java.io.BufferedWriter;
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.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
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;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

// http://lomza.totem-soft.com/tutorial-scan-barcodes-with-zxing-library-intent-integration/

// http://blog.whomeninja.in/android-barcode-scanner-vertical-orientation-and-camera-flash/

// http://babe.ilandroid.com/android-zxing-change-orientation-to-portrait.html

// https://www.supinfo.com/articles/single/4479--orientation-verticale-scanneur-barcode-lib-zxing-mode-portrait-flash-appareil-photo

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

    Button btn;
    Button btnDel;

    private static final String STATE_LIST = "State Adapter Data";

    final Activity activity = this;

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

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

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

        if (savedInstanceState != null)
        {
            list = (ArrayList<String>) savedInstanceState.getSerializable(STATE_LIST);
        }

    //    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 (TextUtils.isEmpty(edit.getText().toString())) {
                    Toast.makeText(getApplicationContext(), "Empty !.", Toast.LENGTH_SHORT).show();
                } else {
                    //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();
                    }
                }
            }
*/
            public void onClick(View v)
            {
                IntentIntegrator integrator = new IntentIntegrator(activity);
                integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);


                //integrator.set setScanningRectangle(300, 300);

                integrator.setPrompt("Scan");
                integrator.setCameraId(0);

                integrator.setOrientationLocked(true);
                //integrator.setOrientationLocked(false);

                integrator.setBeepEnabled(false);
                integrator.setBarcodeImageEnabled(false);

                //integrator.setBarcodeImageEnabled(true);

                integrator.initiateScan();


            }


        };

        /** 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(ScanBarcodeActivity.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);
    }


    @Override
    public void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        outState.putSerializable(STATE_LIST, list);
    }

    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();
        }


    }


    // https://github.com/journeyapps/zxing-android-embedded/tree/master/sample/src/main/java/example/zxing

    // https://github.com/yushulx/Android-Barcode-Reader

    // http://www.codepool.biz/how-to-implement-a-simple-barcode-scan-application-on-android.html

    // Get the scanned image of barcode using zxing barcode scanner

    // https://stackoverflow.com/questions/17953071/get-the-scanned-image-of-barcode-using-zxing-barcode-scanner

    // https://stackoverflow.com/questions/29649673/scan-barcode-from-an-image-in-gallery-android

    // https://codelabs.developers.google.com/codelabs/bar-codes/#5

    // MultiFormatReader

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null)
        {
            if(result.getContents() == null)
            {
                Log.d("MainActivity", "Cancelled scan");
                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
            }

            else
            {
                Log.d("MainActivity", "Scanned");
                Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();

                //list.add(edit.getText().toString());
                //edit.setText("");

                String toto = result.getContents();
                list.add(toto);
                adapter.notifyDataSetChanged();
            }
        }

        else
        {
            // This is important, otherwise the result will not be passed to the fragment
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

/*
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
        if (scanningResult != null) {
            String scanContent = scanningResult.getContents();
            String scanFormat = scanningResult.getFormatName();

            txtFormat.setText(scanFormat);
            txtContent.setText(scanContent);
        } else {
            Toast toast = Toast.makeText(getApplicationContext(),
                    "No scan data received!", Toast.LENGTH_SHORT);
            toast.show();
        }
*/

}

/*
    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();
        }
    }
  */

/*  dans le manifest

                <activity
            android:name="com.journeyapps.barcodescanner.CaptureActivity"
                    android:screenOrientation="portrait"
                    tools:replace="android:screenOrientation"
                    android:stateNotNeeded="true"/>
*/