/**
 * $URL$
 * DAAND
 * Copyright (C) 2004 - 2013, INSIDE Secure BV.  All rights reserved.
 */
package com.insidesecure.drm.android.reference.activities;

import java.util.*;





import android.app.*;
import android.content.*;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import com.insidesecure.drm.android.reference.xoplayer.R;
import com.insidesecure.drmagent.*;
import com.insidesecure.drm.android.reference.DRMAgentDelegate;

public class CacheMediaManagementActivity extends ListActivity implements ListView.OnScrollListener
{
    protected SlowAdapter _adapter;
    public List<DRMCacheInfo> _drmCacheInfos;
    private boolean mBusy;
    protected static Dialog sLastDisplayedDialog;


    @Override
    protected void onSaveInstanceState(final Bundle outState)
    {
        super.onSaveInstanceState(outState);
        if (sLastDisplayedDialog != null)
        {
            sLastDisplayedDialog.dismiss();
        }
    }

    @Override
    protected void onRestoreInstanceState(final Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);
        if (sLastDisplayedDialog != null)
        {
            sLastDisplayedDialog.show();
        }
    }

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

        loadCacheInfos();

        // Use an existing ListAdapter that will map an array
        // of strings to TextViews
        _adapter = new SlowAdapter(this);
        setListAdapter(_adapter);

        getListView().setOnScrollListener(this);
    }

    /**
     * Will not bind views while the list is scrolling
     */
    protected class SlowAdapter extends BaseAdapter
    {
        private LayoutInflater mInflater;

        public SlowAdapter(Context context)
        {
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        /**
         * The number of items in the list is determined by the number of speeches
         * in our array.
         *
         * @see android.widget.ListAdapter#getCount()
         */
        public int getCount()
        {
            return getCacheSize();
        }


        /**
         * Since the data comes from an array, just returning the index is
         * sufficent to get at the data. If we were using a more complex data
         * structure, we would return whatever object represents one row in the
         * list.
         *
         * @see android.widget.ListAdapter#getItem(int)
         */
        public Object getItem(int position)
        {
            return getCacheElement(position);
        }

        /**
         * Use the array index as a unique id.
         *
         * @see android.widget.ListAdapter#getItemId(int)
         */
        public long getItemId(int position)
        {
            return position;
        }

        /**
         * Make a view to hold each row.
         *
         * @see android.widget.ListAdapter#getView(int, android.view.View,
         *      android.view.ViewGroup)
         */
        public View getView(final int position, View convertView, ViewGroup parent)
        {
            View listItem;

            if (convertView == null)
            {
                listItem = mInflater.inflate(R.layout.cache_item, parent, false);
            }
            else
            {
                listItem = convertView;
            }

            listItem.setClickable(false);
            listItem.setVisibility(View.VISIBLE);

            listItem.setLongClickable(true);
            listItem.setOnLongClickListener(new View.OnLongClickListener()
            {
                public boolean onLongClick(final View view)
                {
                    AlertDialog customAlertDialog = createCustomAlertDialog(getText(R.string.clear_cache_single_content_warning), new DialogInterface.OnClickListener()
                    {
                        public void onClick(DialogInterface dlg, int sumthin)
                        {
                            getOnClickAction(position);
                        }
                    });
                    sLastDisplayedDialog = customAlertDialog;
                    customAlertDialog.show();
                    return true;
                }
            });

            if (!mBusy)
            {
                sortListItem(position, listItem);
            }
            else
            {
                TextView text = (TextView) listItem.findViewById(R.id.cache_item_details);
                text.setText("Loading...");
                text = (TextView) listItem.findViewById(R.id.cache_item_url);
                text.setVisibility(View.GONE);
                // Non-null tag means the view still needs to load it's data
                listItem.setTag(this);
            }

            return listItem;
        }
    }

    protected AlertDialog createCustomAlertDialog(CharSequence message, DialogInterface.OnClickListener onClickListener)
    {
        final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setTitle(R.string.warning);
        alertDialogBuilder.setMessage(message);
        alertDialogBuilder.setInverseBackgroundForced(true);
        alertDialogBuilder.setPositiveButton(getText(R.string.Yes), onClickListener);
        alertDialogBuilder.setNegativeButton(getText(R.string.No), new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dlg, int sumthin)
            {
                // Do nothing?
                sLastDisplayedDialog = null;
            }
        });


        return alertDialogBuilder.create();
    }

    protected void getOnClickAction(int position)
    {
        final DRMCacheInfo drmCacheInfo = _drmCacheInfos.get(position);
        DRMAgentDelegate.getDRMAgentInstance(CacheMediaManagementActivity.this).getDownloadManager().clearCachedData(drmCacheInfo.getURI());
        _drmCacheInfos = DRMAgentDelegate.getDRMAgentInstance(CacheMediaManagementActivity.this).getDownloadManager().retrieveDRMCacheInfo();
        _adapter.notifyDataSetChanged();
        sLastDisplayedDialog = null;
    }

    protected void  loadCacheInfos()
    {
        _drmCacheInfos = DRMAgentDelegate.getDRMAgentInstance(CacheMediaManagementActivity.this).getDownloadManager().retrieveDRMCacheInfo();
    }

    protected int getCacheSize()
    {
        return _drmCacheInfos.size();
    }

    protected Object getCacheElement(int position)
    {
        return _drmCacheInfos.get(position);
    }

    protected void sortListItem(final int position, final View listItem)
    {
        final DRMCacheInfo drmCacheInfo = _drmCacheInfos.get(position);

        TextView text = (TextView) listItem.findViewById(R.id.cache_item_details);
        text.setText("Duration/size: " + drmCacheInfo.getDurationCached() + " sec/" + (drmCacheInfo.getCachedDataSize(false) / 1024) + "kB");
        text = (TextView) listItem.findViewById(R.id.cache_item_url);
        text.setVisibility(View.VISIBLE);

        text = (TextView) listItem.findViewById(R.id.cache_item_url);
        text.setText("URL: " + drmCacheInfo.getURI().toString());
        text = (TextView) listItem.findViewById(R.id.cache_item_url);
        text.setVisibility(View.VISIBLE);

        text = (TextView) listItem.findViewById(R.id.cache_item_last_read);
        text.setVisibility(View.VISIBLE);
        text.setText("Last Used: " + new Date(drmCacheInfo.getLastRead()).toString());

        text = (TextView) listItem.findViewById(R.id.cache_item_last_write);
        text.setText("Last Write: " + new Date(drmCacheInfo.getLastWrite()).toString());
        text.setVisibility(View.VISIBLE);

        text = (TextView) listItem.findViewById(R.id.cache_item_bitrate);
        text.setText("Cached Bitrate: " + (drmCacheInfo.getCachedVideoQualityLevel().mBitRate == -1 ? "N/A" : "" + drmCacheInfo.getCachedVideoQualityLevel().mBitRate));
        text.setVisibility(View.VISIBLE);

        text = (TextView) listItem.findViewById(R.id.cache_item_audio_language);

        StringBuilder sb = new StringBuilder();
        for (Iterator<DRMContent.AudioTrack> iterator = drmCacheInfo.getCachedAudioTracks().iterator(); iterator.hasNext(); )
        {
            DRMContent.AudioTrack next = iterator.next();
            sb.append(next.mName + "(" + next.mLanguage +")");
            if (iterator.hasNext())
            {
                sb.append(", ");
            }

        }

        text.setText("Cached Audio Track(s): " + sb.toString());
        text.setVisibility(View.VISIBLE);

        listItem.setTag(null);
    }


    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                         int totalItemCount)
    {
    }


    public void onScrollStateChanged(AbsListView view, int scrollState)
    {
        switch (scrollState)
        {
            case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                mBusy = false;

                int first = view.getFirstVisiblePosition();
                int count = view.getChildCount();
                for (int i = first; i < count; i++)
                {
                    View t = view.getChildAt(i);
                    if (t.getTag() != null)
                    {
                        sortListItem(i, t);
                    }
                }
                break;
            case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                mBusy = true;
                break;
            case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
                mBusy = true;
                break;
        }
    }

}
