package fr.ensisa.lob.supercallrecorder;


import android.Manifest;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ArrayList<Record> recordList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Receiver class which extends BroadcastReceiver
        ContentResolver cr = getContentResolver();
        String[] permission = {"android.permission.READ_PHONE_STATE",
                "android.permission.READ_CONTACTS",
                "android.permission.WRITE_EXTERNAL_STORAGE",
               // "android.permission.STORAGE",
                "android.permission.RECORD_AUDIO",
                "android.permission.PROCESS_OUTGOING_CALLS",
                "android.permission.READ_PHONE_STATE",
                //"android.permission.CAPTURE_AUDIO_OUTPUT",
                "android.permission.RECORD_AUDIO"};
        for (String p : permission)
        {
            if ( ContextCompat.checkSelfPermission( this,p ) != PackageManager.PERMISSION_GRANTED )
            {
                requestPermissions(new String[]{
                                Manifest.permission.READ_PHONE_STATE,
                                Manifest.permission.READ_CONTACTS,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                //Manifest.permission.STORAGE,
                                Manifest.permission.RECORD_AUDIO,

                                Manifest.permission.PROCESS_OUTGOING_CALLS,
                                Manifest.permission.READ_PHONE_STATE,
                                Manifest.permission.CAPTURE_AUDIO_OUTPUT,
                                Manifest.permission.RECORD_AUDIO},
                        R.string.app_name);
            }

        }

        ListView lv = (ListView) findViewById(R.id.listview);


        generateListContent();
        lv.setAdapter(new MyListAdapter(this, R.layout.custom_list, recordList));
        //MediaRecorder.OutputFormat.THREE_GPP;
    }

    public void generateListContent() {
        final String TEXT_TYPE = " TEXT";
        final String BOOLEAN_TYPE = " INTEGER";
        final String COMMA_SEP = ",";
        RecordDbHelper mDbHelper = new RecordDbHelper(this);
        SQLiteDatabase db = mDbHelper.getReadableDatabase();
        recordList.clear();
        db.rawQuery("CREATE TABLE IF NOT EXISTS "+ RecordDbHelper.RecordEntry.TABLE_NAME + " (" +
                RecordDbHelper.RecordEntry._ID + " INTEGER PRIMARY KEY," +
                RecordDbHelper.RecordEntry.COLUMN_NAME_CONTACTNAME + TEXT_TYPE + COMMA_SEP +
                RecordDbHelper.RecordEntry.COLUMN_NAME_INCOMING + BOOLEAN_TYPE + COMMA_SEP +
                RecordDbHelper.RecordEntry.COLUMN_NAME_DATE + TEXT_TYPE + COMMA_SEP +
                RecordDbHelper.RecordEntry.COLUMN_NAME_FILENAME + TEXT_TYPE + COMMA_SEP +
                RecordDbHelper.RecordEntry.COLUMN_NAME_SALT + TEXT_TYPE + " )", null);



        Cursor c = db.rawQuery("SELECT "+RecordDbHelper.RecordEntry.COLUMN_NAME_FILENAME+ COMMA_SEP +
                RecordDbHelper.RecordEntry.COLUMN_NAME_DATE + COMMA_SEP +
                RecordDbHelper.RecordEntry.COLUMN_NAME_INCOMING + COMMA_SEP +
                RecordDbHelper.RecordEntry.COLUMN_NAME_CONTACTNAME + COMMA_SEP+
                RecordDbHelper.RecordEntry.COLUMN_NAME_SALT +" FROM "+ RecordDbHelper.RecordEntry.TABLE_NAME, null);

        if(c.moveToFirst()){
            do{
                final int INDEX_CONTACTNAME = c.getColumnIndex(RecordDbHelper.RecordEntry.COLUMN_NAME_CONTACTNAME);
                final int INDEX_DATE = c.getColumnIndex(RecordDbHelper.RecordEntry.COLUMN_NAME_DATE);
                final int INDEX_INCOMING = c.getColumnIndex(RecordDbHelper.RecordEntry.COLUMN_NAME_INCOMING);
                final int INDEX_FILENAME = c.getColumnIndex(RecordDbHelper.RecordEntry.COLUMN_NAME_FILENAME);
                final int INDEX_SALT = c.getColumnIndex(RecordDbHelper.RecordEntry.COLUMN_NAME_SALT);
                recordList.add(
                        new Record(c.getString(INDEX_FILENAME),
                                c.getString(INDEX_DATE),
                                c.getString(INDEX_INCOMING),
                                c.getString(INDEX_CONTACTNAME),
                                c.getString(INDEX_SALT)
                        ));

            }while(c.moveToNext());
        }

        c.close();

    }


    private class MyListAdapter extends ArrayAdapter<Record> {
        private int layout;
        private List<Record> mObjects;
        private MediaPlayer MP;
        private int currentPlayerID = -1;
        private MyListAdapter(Context context, int resource, List<Record> objects) {
            super(context, resource, objects);
            //mObjects = objects;
            layout = resource;
        }



        public  String getContactName(Context context, String phoneNumber) {
            ContentResolver cr = context.getContentResolver();
            Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
            Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
            if (cursor == null) {
                return null;
            }
            String contactName = null;
            if(cursor.moveToFirst()) {
                contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
            }

            if(cursor != null && !cursor.isClosed()) {
                cursor.close();
            }

            return contactName;
        }


        public  String getContactId(Context context, String phoneNumber) {
            ContentResolver contentResolver = context.getContentResolver();

            Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));

            String[] projection = new String[] {ContactsContract.PhoneLookup._ID};

            Cursor cursor =
                    contentResolver.query(
                            uri,
                            projection,
                            null,
                            null,
                            null);

            if(cursor!=null) {
                while(cursor.moveToNext()){
                    String contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
                    return contactId;
                }
                cursor.close();
            }
            return "";
        }


        public InputStream openPhoto(long contactId) {
            Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
            Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
            Cursor cursor = getContentResolver().query(photoUri,
                    new String[] {ContactsContract.Contacts.Photo.PHOTO}, null, null, null);
            if (cursor == null) {
                return null;
            }
            try {
                if (cursor.moveToFirst()) {
                    byte[] data = cursor.getBlob(0);
                    if (data != null) {
                        return new ByteArrayInputStream(data);
                    }
                }
            } finally {
                cursor.close();
            }
            return null;
        }

        public Uri getPhotoUri(long contactId,Context ctx) {
            try {
                Cursor cur = ctx.getContentResolver().query(
                        ContactsContract.Data.CONTENT_URI,
                        null,
                        ContactsContract.Data.CONTACT_ID + "=" + Long.toString(contactId) + " AND "
                                + ContactsContract.Data.MIMETYPE + "='"
                                + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'", null,
                        null);
                if (cur != null) {
                    if (!cur.moveToFirst()) {
                        return null; // no photo
                    }
                } else {
                    return null; // error in cursor process
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
            return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
        }




        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final Record r = recordList.get(position);
            ViewHolder mainViewholder = null;


            if(convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(getContext());
                convertView = inflater.inflate(layout, parent, false);
                convertView.setLongClickable(true);

                ViewHolder viewHolder = new ViewHolder();

                viewHolder.thumbnail = (ImageView) convertView.findViewById(R.id.list_item_thumbnail);
                viewHolder.contactName = (TextView) convertView.findViewById(R.id.list_item_name);
                viewHolder.duration = (TextView) convertView.findViewById(R.id.list_item_duration);
                viewHolder.state = (ImageView) convertView.findViewById(R.id.list_item_state);
                viewHolder.button = (Button) convertView.findViewById(R.id.list_item_btn);
                convertView.setTag(viewHolder);

            }


            mainViewholder = (ViewHolder) convertView.getTag();

            try {

                MediaPlayer mp = new MediaPlayer();
                mp.setDataSource(r.getFileName());
                mp.prepare();
                Date date = new Date(mp.getDuration());
                DateFormat formatter = new SimpleDateFormat("mm:ss");
                String dateFormatted = formatter.format(date);
                mainViewholder.duration.setText(dateFormatted);



                mainViewholder.button.setOnLongClickListener(new View.OnLongClickListener() {

                    public boolean onLongClick(View v) {


                        AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
                        builder1.setMessage(R.string.delete);
                        builder1.setCancelable(true);

                        /*
                        ATTENTION
                        C'EST PAS DANS LE BON ORDRE.

                        ON DIT :
                        OUI         NON
                        PAS :
                        NON         OUI

                        NOM DE NOM
                         */
                        builder1.setPositiveButton(
                                R.string.cancel,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });

                        builder1.setNegativeButton(
                                R.string.confirm,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        this.deleteItem(r.getId());

                                        dialog.cancel();
                                    }

                                    public void deleteItem(long id) {

                                        final String TEXT_TYPE = " TEXT";
                                        final String BOOLEAN_TYPE = " INTEGER";
                                        final String COMMA_SEP = ",";
                                        RecordDbHelper mDbHelper = new RecordDbHelper(getContext());
                                        SQLiteDatabase db = mDbHelper.getReadableDatabase();

                                        File file = new File(r.getFileName());
                                        boolean deleted = file.delete();
                                        db.delete(RecordDbHelper.RecordEntry.TABLE_NAME,RecordDbHelper.RecordEntry.COLUMN_NAME_FILENAME+"=?",new String[]{r.getFileName()});

                                    }
                                });

                        AlertDialog alert11 = builder1.create();
                        alert11.show();


                        return true;
                    }
                });
                mainViewholder.button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(final View v) {
                        Button vg=(Button)v;

                            if (currentPlayerID == position) // Meme bouton que celui appuye avant
                            {
                                if (MP.isPlaying())
                                {
                                    MP.pause();
                                    vg.setBackgroundResource(R.drawable.img_btn_play);

                                } else
                                {
                                    MP.start();
                                    vg.setBackgroundResource(R.drawable.img_btn_pause);

                                }
                            } else
                            {
                                if (MP != null)
                                {
                                    try {
                                        MP.stop();
                                        MP.reset();
                                        //MP.prepare();
                                        MP.release();
                                        MP=null;
                                        currentPlayerID = -1;
                                        vg.setBackgroundResource(R.drawable.img_btn_play);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }

                                MP = new MediaPlayer();
                                currentPlayerID = position;
                                vg.setBackgroundResource(R.drawable.img_btn_pause);
                                Record r2 = recordList.get(position);
                                try {
                                    MP.setDataSource(r2.getFileName());
                                    MP.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                                        @Override
                                        public void onCompletion(MediaPlayer mp) {
                                            if (MP != null)
                                            {
                                                try {
                                                    MP.stop();
                                                    MP.reset();
                                                    //MP.prepare();
                                                    MP.release();
                                                    MP=null;
                                                    currentPlayerID = -1;
                                                    Button vg = (Button) v;
                                                    vg.setBackgroundResource(R.drawable.img_btn_play);
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        }

                                    });
                                    MP.prepare();
                                    MP.start();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }



                    }
                });

            } catch (IOException e) {
              e.printStackTrace();
            }
            String phoneNumber = null;
            String contactName = "";

            try   {
                phoneNumber = r.getContactName();
                contactName = phoneNumber;
            }

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

            mainViewholder.thumbnail.setImageResource(R.drawable.img_default);
            try {
                contactName = getContactName(getContext(),phoneNumber)!=null ? getContactName(getContext(),phoneNumber) : r.getContactName();
                Long contactId = Long.parseLong(getContactId(getContext(),phoneNumber));
                Uri u = getPhotoUri(contactId,getContext());
                if (u != null) {
                    mainViewholder.thumbnail.setImageURI(u);
                } else {
                    mainViewholder.thumbnail.setImageResource(R.drawable.img_default);
                }
            } catch (Exception e)
            {
                Log.e("Crash",e.toString());
            }

            int callState = r.isIncoming()?R.drawable.img_incoming:R.drawable.img_outgoing;



            mainViewholder.contactName.setText(contactName);
            mainViewholder.state.setBackgroundResource(callState);

            return convertView;
        }
    }



    public class ViewHolder {

        ImageView thumbnail;
        TextView contactName;
        ImageView state;
        TextView duration;
        Button button;
    }


}
