package party.bami.eqfix.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;

import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cafe.adriel.androidaudioconverter.AndroidAudioConverter;
import cafe.adriel.androidaudioconverter.callback.IConvertCallback;
import cafe.adriel.androidaudioconverter.callback.ILoadCallback;
import cafe.adriel.androidaudioconverter.model.AudioFormat;
import party.bami.eqfix.R;
import party.bami.eqfix.other.ExpandableListAdapter;
import party.bami.eqfix.other.FileUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static party.bami.eqfix.Musicplayer.ParseDirectories.RegisterDirectory;
import static party.bami.eqfix.Musicplayer.ParseDirectories.getDirectories;
import static party.bami.eqfix.Musicplayer.ParseDirectories.getFiles;
import static party.bami.eqfix.other.ParseDirectories.RegisterDirectorySave;

public class SettingsActivity extends AppCompatActivity {



    /// dir selection //

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
            case 5000:
                String path = FileUtil.getFullPathFromTreeUri(data.getData(),this);
                RegisterDirectory(getApplicationContext(),path);
                Snackbar.make(findViewById(android.R.id.content), "Added directory " + path, Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
                break;
            case 5010:
                String path2 = FileUtil.getFullPathFromTreeUri(data.getData(),this);
                RegisterDirectorySave(getApplicationContext(),path2);
                Snackbar.make(findViewById(android.R.id.content), "Added directory " + path2, Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
        }
    }

    ///dir




    ////AndroidHive**


    ExpandableListAdapter listAdapter;
    ExpandableListView expListView;
    List<String> listDataHeader;
    HashMap<String, List<String>> listDataChild;
    ////


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

        ////FAB



        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

        // Navigation view header

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                Intent i = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
                i.addCategory(Intent.CATEGORY_DEFAULT);
                i.putExtra("android.content.extra.SHOW_ADVANCED", true);
                i.putExtra("android.content.extra.FANCY", true);
                i.putExtra("android.content.extra.SHOW_FILESIZE", true);

                startActivityForResult(Intent.createChooser(i, "Choose directory"), 5000);



            }
        });



        FloatingActionButton fabSave = (FloatingActionButton) findViewById(R.id.fabSave);

        // Navigation view header

        fabSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                Intent i = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
                i.addCategory(Intent.CATEGORY_DEFAULT);
                i.putExtra("android.content.extra.SHOW_ADVANCED", true);
                i.putExtra("android.content.extra.FANCY", true);
                i.putExtra("android.content.extra.SHOW_FILESIZE", true);

                startActivityForResult(Intent.createChooser(i, "Choose directory"), 5010);



            }
        });
        ////




        ///LISTVIEW//

        // get the listview
        expListView = (ExpandableListView) findViewById(R.id.settings_listview);

        // preparing list data
        prepareListData();

        listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

        // setting list adapter
        expListView.setAdapter(listAdapter);

        // Listview Group click listener
        expListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                                        int groupPosition, long id) {
                // Toast.makeText(getApplicationContext(),
                // "Group Clicked " + listDataHeader.get(groupPosition),
                // Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        // Listview Group expanded listener
        expListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {

            @Override
            public void onGroupExpand(int groupPosition) {
                Toast.makeText(getApplicationContext(),
                        listDataHeader.get(groupPosition) + " Expanded",
                        Toast.LENGTH_SHORT).show();
            }
        });

        // Listview Group collasped listener
        expListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {

            @Override
            public void onGroupCollapse(int groupPosition) {
                Toast.makeText(getApplicationContext(),
                        listDataHeader.get(groupPosition) + " Collapsed",
                        Toast.LENGTH_SHORT).show();

            }
        });

        // Listview on child click listener
        expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
                // TODO Auto-generated method stub
                Toast.makeText(
                        getApplicationContext(),
                        listDataHeader.get(groupPosition)
                                + " : "
                                + listDataChild.get(
                                listDataHeader.get(groupPosition)).get(
                                childPosition), Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
        });



        /////






        AndroidAudioConverter.load(this, new ILoadCallback() {
            @Override
            public void onSuccess() {
                // Great!
                System.out.println("Loaded");
            }
            @Override
            public void onFailure(Exception error) {
                // FFmpeg is not supported by device
                System.out.println("Loade");
            }
        });    }

        /////



    /*
     * Preparing the list data
     */
    private void prepareListData() {
//        getDirectories(Context context)
//        getFiles(path)

        String[] paths = getDirectories(getApplicationContext());
        listDataHeader = new ArrayList<String>();
        listDataChild = new HashMap<String, List<String>>();

        if (paths!=null){



            for (int i = 0; i < paths.length; i++) {
                listDataHeader.add(paths[i]);
                File[] fileList = getFiles(paths[i]);
                List<String> placeholder1 = new ArrayList<String>();
                for (int y = 0; y < fileList.length; y++) {
                    placeholder1.add(fileList[y].getName());
                }
                listDataChild.put(listDataHeader.get(i), placeholder1);
            }
        }else{
        listDataHeader.add("No directories");
        List<String> placeholder1 = new ArrayList<String>();
        placeholder1.add("No files");



        listDataChild.put(listDataHeader.get(0), placeholder1); // Header, Child data

        }



        // Adding child data
//        listDataHeader.add("Placeholder");
//        listDataHeader.add("Placeholder");
//        listDataHeader.add("Placeholder");

        // Adding child data
//        List<String> placeholder1 = new ArrayList<String>();
//        placeholder1.add("Placeholder");
//
//        List<String> placeholder2 = new ArrayList<String>();
//        placeholder2.add("Placeholder");
//
//
//        List<String> placeholder3 = new ArrayList<String>();
//        placeholder3.add("Placeholder");


//        listDataChild.put(listDataHeader.get(0), placeholder1); // Header, Child data
//        listDataChild.put(listDataHeader.get(1), placeholder2);
//        listDataChild.put(listDataHeader.get(2), placeholder3);
    }
    /////


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == android.R.id.home) {
            // finish the activity
//            convertAudio();
            //TODO: MO edit uncomment
            onBackPressed();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    public void convertAudio(){
        /**
         *  Update with a valid audio file!
         *  Supported formats: {@link AndroidAudioConverter.AudioFormat}
         */
        /* Makes sure we have the right permissions. */

        File wavFile = new File(Environment.getExternalStorageDirectory(), "test2.mp3");

        IConvertCallback callback = new IConvertCallback() {
            @Override
            public void onSuccess(File convertedFile) {
                Toast.makeText(SettingsActivity.this, "SUCCESS: " + convertedFile.getPath(), Toast.LENGTH_LONG).show();
            }
            @Override
            public void onFailure(Exception error) {
                Toast.makeText(SettingsActivity.this,"ERROR: " + error.getMessage(), Toast.LENGTH_LONG).show();
            }
        };
        Toast.makeText(this, "Converting audio file...", Toast.LENGTH_SHORT).show();
        AndroidAudioConverter.with(this)
                .setFile(wavFile)
                .setFormat(AudioFormat.WAV)
                .setCallback(callback)
                .convert();
    }
}
