package com.example.patrice.http01;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
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.OutputStream;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import static com.example.patrice.http01.R.id.imageView;

/**
 * Created by Patrice on 20/12/2017.
 */

// http://androidsnips.blogspot.fr/2010/08/show-image-from-internet-in-imageview.html

//http://androidsnips.blogspot.fr/2010/08/send-request-to-server-and-read.html

    // http://androidsnips.blogspot.fr/2010/08/upload-file-to-remote-server-in-android.html

public class tools01
{

    private String totostr;
    private String url = "http://www.analog-design.net/MP3/json02.php";

    private Bitmap bitmap = null;
    Bitmap b;
    ImageView img;


    public void accessWebService()
    {
        JsonReadTask task = new JsonReadTask();
        task.execute(new String[] { url });

         }

    public void toto()
    {
        //////////// Doit être debugger !!!! /////////
        //DownloadFileFromURL action = new DownloadFileFromURL();
        //action.execute("http://www.analog-design.net/MP3/listing.txt");

        //////////// OK /////////
        //read();

        //////////// OK /////////
        //String url = "http://analog-design.net/WORKAREA/WEBSITE/Codebar/http_request.php?data=75";
        //http_request tache = new http_request();
        //tache.execute(new String[] { url });


        //information info = new information();
        //info.execute();

    }

    public void download_image()
    {
        //img = (ImageView)findViewById(R.id.imageView);
        //img.setImageDrawable(null);



        async_download_image objet = new async_download_image();
        objet.execute();
    }


    public  void read()
    {
        if (!Environment.getExternalStorageState().equals
        (
            Environment.MEDIA_MOUNTED))
            {
                Log.d("LOG_TAG", "SD na " + Environment.getExternalStorageState());
                return;
            }

            File sdPath = Environment.getExternalStorageDirectory();
            sdPath = new File(sdPath.getAbsolutePath() + "/plus");
            File sdFile = new File(sdPath, "settings.dat");

            try
            {
                BufferedReader br = new BufferedReader(new FileReader(sdFile));
                String str = "";
                while ((str = br.readLine()) != null)
                {
                    String[] words = str.split(",");
                    // do some work
                }
                Log.d("LOG_TAG", str);

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

    private class JsonReadTask extends AsyncTask<String, Void, String>
    {
        @Override
        protected String doInBackground(String... params)
        {
            URL url;

            try
            {

                url = new URL("http://www.analog-design.net/MP3/listing.txt");
                BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream()));

                StringBuilder str = new StringBuilder();
                String line;
                while ((line = in.readLine()) != null)
                    str.append(line);
                in.close();

                totostr = str.toString();

            }

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



            return null;
        }



        @Override
        protected void onPostExecute(String result)
        {
            /*
            File file = new File("/mnt/sdcard/play_list.txt");
            Writer fileWriter = null;
            BufferedWriter bufferedWriter = null;

            try {

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

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


                }

                bufferedWriter.close();


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

    private class DownloadFileFromURL  extends AsyncTask<String, String, String>
    {

        @Override
        protected String doInBackground(String... f_url)
        {
            /*
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();

                // download the file
                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                // Output stream
                OutputStream output = new FileOutputStream("download_file.txt");

                byte data[] = new byte[1024];

                while ((count = input.read(data)) != -1)
                {

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;*/

            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();
                InputStream input = new BufferedInputStream(url.openStream(), 8192);
                File SDCardRoot = Environment.getExternalStorageDirectory();
                SDCardRoot = new File(SDCardRoot.getAbsolutePath() + "/plus");
                SDCardRoot.mkdir();
                File file = new File(SDCardRoot,"settings.dat");
                FileOutputStream output = new FileOutputStream(file);
                byte data[] = new byte[1024];

                while ((count = input.read(data)) != -1) {
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }
            return null;

        }

    }



    public String Download(String Url)
    {
        File file;

        String filepath=null;

        try {
            //set the download URL, a url that points to a file on the internet
            //this is the file to be downloaded
            URL url = new URL(Url);
            //create the new connection
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            //set up some things on the connection
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            //and connect!
            urlConnection.connect();
            //set the path where we want to save the file
            //in this case, going to save it on the root directory of the
            //sd card.
            File SDCardRoot = Environment.getExternalStorageDirectory();
            //create a new file, specifying the path, and the filename
            //which we want to save the file as.

            String filename= "tartuffe_File.txt";   // you can download to any type of file ex:.jpeg (image) ,.txt(text file),.mp3 (audio file)
            Log.i("Local filename:",""+filename);
            file = new File(SDCardRoot,filename);
            if(file.createNewFile())
            {
                file.createNewFile();
            }

            //this will be used to write the downloaded data into the file we created
            FileOutputStream fileOutput = new FileOutputStream(file);

            //this will be used in reading the data from the internet
            InputStream inputStream = urlConnection.getInputStream();

            //this is the total size of the file
            int totalSize = urlConnection.getContentLength();
            //variable to store total downloaded bytes
            int downloadedSize = 0;

            //create a buffer...
            byte[] buffer = new byte[1024];
            int bufferLength = 0; //used to store a temporary size of the buffer

            //now, read through the input buffer and write the contents to the file
            while ( (bufferLength = inputStream.read(buffer)) > 0 )
            {
                //add the data in the buffer to the file in the file output stream (the file on the sd card
                fileOutput.write(buffer, 0, bufferLength);
                //add up the size so we know how much is downloaded
                downloadedSize += bufferLength;
                //this is where you would do something to report the prgress, like this maybe
                Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;

            }
            //close the output stream when done
            fileOutput.close();
            if(downloadedSize==totalSize)
                filepath=file.getPath();

            //catch some possible errors...
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            filepath=null;
            e.printStackTrace();
        }
        Log.i("filepath:"," "+filepath) ;

        return filepath;

    }

    /***************************************************************************/
    public class http_request extends AsyncTask<String, String, String>
    {
        @Override
        protected String doInBackground(String... urlStr)
        {
            try
            {
                    URL mUrl = new URL(urlStr[0]);
                    HttpURLConnection httpConnection = (HttpURLConnection) mUrl.openConnection();
                    httpConnection.setRequestMethod("GET");
                    httpConnection.setRequestProperty("Content-length", "0");
                    httpConnection.setUseCaches(false);
                    httpConnection.setAllowUserInteraction(false);
                    httpConnection.setConnectTimeout(100000);
                    httpConnection.setReadTimeout(100000);

                    httpConnection.connect();

                    int responseCode = httpConnection.getResponseCode();

                    if (responseCode == HttpURLConnection.HTTP_OK)
                    {
                        BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
                        StringBuilder sb = new StringBuilder();
                        String line;
                        while ((line = br.readLine()) != null)
                        {
                            sb.append(line + "\n");
                        }
                        br.close();
                        return sb.toString();
                    }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String s)
        {
            super.onPostExecute(s);


        }
    }

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

    public class async_download_image extends AsyncTask<String, String, Bitmap>
    {

        /*protected void onPreExecute()
        {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading Image ....");
            pDialog.show();

        }*/

        @Override
        protected Bitmap doInBackground(String... arg0) {

            HttpURLConnection connection = null;
            URL url = null;

            try
            {

                url = new URL("http://www.analog-design.net/WORKAREA/WEBSITE/Codebar/caps.jpg");
                connection = (HttpURLConnection) url.openConnection();
                //connection.addRequestProperty(BConstant.WEB_SERVICES_COOKIES, cookie);
                connection.setDoOutput(true);
                connection.connect();

                ////// OK /////
                //URL url_str = new URL("http://www.analog-design.net/WORKAREA/WEBSITE/Codebar/caps.jpg");
                //InputStream is = new BufferedInputStream(url_str.openStream(), 8192);
                //bitmap = BitmapFactory.decodeStream(is);
            }

            catch (IOException e1)
            {
                e1.printStackTrace();
            }

            //File folderDir = null;
            //folderDir = new File(getExternalFilesDir("Directory Name") + "/Files");
            //File file = new File(folderDir, fName);

            String filename = "xxpippo.jpg";
            File sd = Environment.getExternalStorageDirectory();
            File dest = new File(sd, filename);



            try
            {
                InputStream inputStream = connection.getInputStream();
                BufferedInputStream bufferedInputStream = null;
                bufferedInputStream = new BufferedInputStream(inputStream, 1024 * 5);

               // bitmap = BitmapFactory.decodeStream(inputStream);

                FileOutputStream fileOutputStream = new FileOutputStream(dest); // folderDir + "/" + fName
                byte[] buffer = new byte[1024];
                int len1 = 0;

                while ((len1 = inputStream.read(buffer)) != -1)
                {
                    fileOutputStream.write(buffer, 0, len1);
                }

                bufferedInputStream.close();
                fileOutputStream.close();
                inputStream.close();
                connection.disconnect();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap image)
        {

            if(image != null)
            {


                img.setImageBitmap(bitmap);


               /* ImageView imageView = this.containerImageView.get();
                if (imageView != null) {
                    imageView.setImageBitmap(result);
                }

                img.setImageBitmap(bitmap);
                String msg = "OK";*/
            }

            /*else
            {
                pDialog.dismiss();
                Toast.makeText(MainActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
            }*/


        }
    }




}
