package com.appli.gui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import android.widget.AdapterView.OnItemClickListener;
import java.util.List;
import java.util.Map;

import com.appli.patoche.R;

import org.apache.http.ProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import static com.appli.patoche.R.id.list_mp3;


// http://www.coderzheaven.com/2012/03/29/uploading-audio-video-or-image-files-from-android-to-server/

// https://stackoverflow.com/questions/9500138/listing-files-of-a-folder-present-in-the-http-server

// https://github.com/vishalvijay/Android-Server-Directory-Listing

// https://www.androidhive.info/2012/01/android-json-parsing-tutorial/

// https://www.javatpoint.com/android-json-parsing-tutorial

// https://itekblog.com/php-android-conversation-using-json-pt-1/

//https://www.akawebdesign.com/2009/08/18/json-formatting-in-php/

//https://www.javacodegeeks.com/2013/10/android-json-tutorial-create-and-parse-json-data.html


//https://www.androidhive.info/2012/01/android-json-parsing-tutorial/   +++++ source dessous mega bien

public class MP3 extends Activity
{
    Button buttonStop,buttonStart ;
    String AudioURL = "https://www.android-examples.com/wp-content/uploads/2016/04/Thunder-rumble.mp3";
    MediaPlayer mediaplayer;

    //String url = "[\"some_photo_from_gdansk_poland.jpg|23-12-2017|19:22:24|31643\",\"src|02-12-2017|21:45:21|0\",\"tasks|02-12-2017|21:45:21|0\",\"test|02-12-2017|21:45:21|0\",\"test.php|12-07-2017|23:28:44|1105\",\"test01.php|17-12-2017|17:55:09|2815\",\"toto.java|18-12-2017|21:41:38|6268\",\"type-definitions|02-12-2017|21:45:21|0\",\"upcdatabase01.php|16-12-2017|22:02:05|2699\",\"upcdatabase02.php|16-12-2017|22:13:47|920\",\"upload01.php|19-12-2017|23:38:57|274\",\"upload02.php|20-12-2017|11:07:52|269\",\"upload_asyntask01.php|22-12-2017|10:34:12|376\",\"upload_cam_capture01.php|21-12-2017|22:12:03|278\",\"upload_file.php|23-12-2017|18:16:58|1895\",\"VERSION|12-07-2017|23:28:44|5\",\"webpack.config.js|07-06-2017|12:53:26|920\",\"webpack.config.min.js|07-06-2017|12:53:26|490\",\"webpack.node.config.js|07-06-2017|12:53:26|714\",\"xxpippo.jpg|23-12-2017|19:15:11|66967\"]";

    private ProgressDialog pDialog;

    private String TAG = "TAG";

    String url = "https://api.androidhive.info/contacts/";


    String adresse  = "http://analog-design.net/WORKAREA/WEBSITE/Codebar/json001.php";

    private ListView lv;

    ArrayList<HashMap<String, String>> MP3List;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview_mp3_layout); // mp3_layout

        lv = (ListView) findViewById(list_mp3);

        //buttonStart = (Button)findViewById(R.id.button1);
        //buttonStop = (Button)findViewById(R.id.button2);

        mediaplayer = new MediaPlayer();
        mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

        MP3List = new ArrayList<>();

        new GetMP3().execute();
/*
        buttonStart.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                try
                {
                    new GetContacts().execute();
                    //mediaplayer.setDataSource(AudioURL);
                    //mediaplayer.prepare();
                }

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

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

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

                //mediaplayer.start();

            }
        });

        buttonStop.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                mediaplayer.stop();
            }
        });
*/

        lv.setOnItemClickListener(new OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                //Object listItem = lv.getItemAtPosition(position); ??? je sais pas comment le traiter pour extraire les datas ???
                 HashMap<String, Object> map = (HashMap<String, Object>) lv.getItemAtPosition(position);
                 //Map<String, Object> mapping = (Map<String, Object>) lv.getItemAtPosition(position);
                 //String r = (String) mapping.get("name");

                 String mp3_titre = (String) map.get("name");
                 Intent i = new Intent(getApplicationContext(), player_mp3.class);
                 i.putExtra("mp3_titre", mp3_titre);
                 startActivity(i);
            }
        });

    }

    private class GetMP3 extends AsyncTask<Void, Void, Void>
    {

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            pDialog = new ProgressDialog(MP3.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0)
        {
            HttpHandler sh = new HttpHandler();

            String jsonStr = sh.makeServiceCall(adresse); // url

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null)
            {
                try
                {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray MP3_titre = jsonObj.getJSONArray("MP3_file");

                    for (int i = 0; i < MP3_titre.length(); i++)
                    {
                        JSONObject c = MP3_titre.getJSONObject(i);
                        String name = c.getString("name");
                        String date = c.getString("date");
                        String size = c.getString("size");
                        //String address = c.getString("address");
                        //String gender = c.getString("gender");

                        // Phone node is JSON Object
                        //JSONObject phone = c.getJSONObject("phone");
                        //String mobile = phone.getString("mobile");
                        //String home = phone.getString("home");
                        //String office = phone.getString("office");

                        // tmp hash map for single contact
                        HashMap<String, String> MP3_elements = new HashMap<>();

                        // adding each child node to HashMap key => value
                        MP3_elements.put("name", name);
                        MP3_elements.put("date", date);
                        MP3_elements.put("size", size);
                        //contact.put("mobile", mobile);

                        MP3List.add(MP3_elements);
                    }
                }

                catch (final JSONException e)
                {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }

            else
            {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG).show();
                    }
                });
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if( pDialog.isShowing() )
            {
                pDialog.dismiss();
            }

            ListAdapter adapter = new SimpleAdapter( MP3.this, MP3List, R.layout.listview_items_mp3_layout , new String[]{"name", "date", "size"}, new int[]{R.id.name, R.id.date, R.id.size});
            lv.setAdapter(adapter);
        }

    }
}

class HttpHandler
{
    //private static final String TAG = HttpHandler.class.getSimpleName();

    private String TAG = "TAG";

    public HttpHandler()
    {
    }

    public String makeServiceCall(String reqUrl)
    {
        String response = null;
        try
        {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            //  response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        }
        catch (MalformedURLException e)
        {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        }
        catch (IOException e)
        {
            Log.e(TAG, "IOException: " + e.getMessage());
        }
        catch (Exception e)
        {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is)
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try
        {
            while ((line = reader.readLine()) != null)
            {
                sb.append(line).append('\n');
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                is.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }
}

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

       /*
        Uri myUri = Uri.parse("http://local.ip/folder/music.mp3");
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(this, myUri);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.prepare(); //don't use prepareAsync for mp3 playback
        } catch (IOException e) {
            e.printStackTrace();
        }
        */

        /*
        Uri mp3Uri = Uri.parse("http://local.ip/folder/music.mp3");
        Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(mp3Uri, "audio/mpeg3");
        startActivity(intent);
        */
