package com.viaccessorca.voplayerdemo.adapters;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.viaccessorca.voplayerdemo.R;
import com.viaccessorca.voplayerdemo.database.DatabaseInfo;
import com.viaccessorca.voplayerdemo.mediamgt.LocalFileMediaItem;
import com.viaccessorca.voplayerdemo.mediamgt.MediaItem;
import com.viaccessorca.voplayerdemo.mediamgt.MediaItem.MediaType;
import com.viaccessorca.voplayerdemo.mediamgt.StreamingMediaItem;
import com.viaccessorca.voplayerdemo.mediamgt.StreamingMediaList;
import com.viaccessorca.voplayerdemo.mediamgt.SubtitleMediaItem;

import java.util.ArrayList;
import java.util.List;

public class MediaListAdapter extends BaseExpandableListAdapter {


    public interface onResumeButtonListener {
        public void onResumeButtonClick(int groupId, int childId);
    }

    private static final String TAG = "MediaListAdapter";

    private List<String> groups;

    private List<List<MediaItem>> items;

    private Context context = null;

    private onResumeButtonListener resumeButtonListener;

    public MediaListAdapter(Context ctx) {
        this.context = ctx;
        groups = new ArrayList<String>(0);
        items = new ArrayList<List<MediaItem>>(0);
    }

    public void setData(List<String> groups, List<List<MediaItem>> items) {
        this.groups = groups;
        this.items = items;
    }

    public void setOnResumeButtonListener(onResumeButtonListener listener) {
        resumeButtonListener = listener;
    }

    public Object getChild(int groupPosition, int childPosition) {

        if(groupPosition < groups.size()) {
            if(childPosition < items.get(groupPosition).size()) {
                return items.get(groupPosition).get(childPosition);
            }
        }
        return null;
    }

    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    public int getChildrenCount(int groupPosition) {
        return items.get(groupPosition).size();
    }

    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

        MediaItem mediaItem = (MediaItem) getChild(groupPosition, childPosition);
        MediaType mediaType = mediaItem.getMediaType();

        switch(mediaType) {
        case SUBTITLE_FILE:
            convertView = getViewForSubtitleItem(convertView, parent, (SubtitleMediaItem) mediaItem);
            break;
        case HTTP_STREAMING_MEDIA:
        case HTTP_STREAMING_MEDIA_EBD:
            convertView = getViewForStreamingItem(convertView, parent, (StreamingMediaItem) mediaItem, groupPosition, childPosition);
            break;
        case LOCAL_MEDIA:
            convertView = getViewForLocalFileItem(convertView, parent, (LocalFileMediaItem) mediaItem, groupPosition, childPosition);
            break;
        case MEDIA_PLAYLIST:
            convertView = getViewForPlaylistItem(convertView, parent, (StreamingMediaList) mediaItem, groupPosition, childPosition);
            break;
        default:
            LayoutInflater vi = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.medialist_item, null);
            break;
        }
        return convertView;
    }


    private View getViewForSubtitleItem(View convertView, ViewGroup parent, SubtitleMediaItem subtitleItem) {

        //Log.i(TAG, "getViewForSubtitleItem");
        if(null != convertView) {
            convertView = null;
        }
        View v = convertView;
        LayoutInflater vi = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.subtitlemedia_listitem, null);

        TextView fileNameTxt = (TextView)v.findViewById(R.id.medialist_item_title_txt);
        fileNameTxt.setText(subtitleItem.getDisplayName());
        fileNameTxt.setTextColor(this.context.getResources().getColor(R.color.lowlight_file));

        return v;
    }


    private View getViewForStreamingItem(View convertView, ViewGroup parent, StreamingMediaItem streamingItem, int groupPosition, int childPosition) {

        //Log.i(TAG, "getViewForStreamingItem");
        if(null != convertView) {
            if(null == convertView.findViewById(R.id.medialist_item_icon) ) {
                convertView = null;
            }
        }
        if(null == convertView) {
            LayoutInflater vi = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.medialist_item, null);
        }

        ImageView itemIcon = (ImageView)convertView.findViewById(R.id.medialist_item_icon);
        TextView fileNameTxt = (TextView)convertView.findViewById(R.id.medialist_item_title_txt);
        ProgressBar hlsDownloadProgress = (ProgressBar)convertView.findViewById(R.id.hls_dl_progress);

        DatabaseInfo dbInfo = streamingItem.getAssociatedDBInfo();
        boolean useHLSDownload = false;

        ImageView subtitleIcon = (ImageView)convertView.findViewById(R.id.mediaitem_associated_subtitle_img);
        ImageButton resumeButton = (ImageButton)convertView.findViewById(R.id.mediaitem_associated_resume_time);

        // set CC flag and resume button according to database info
        if( null != dbInfo) {
            //Log.d(TAG, "getViewForStreamingItem - dbInfo for uri " + streamingItem.getMediaUri());
            if (MediaType.HTTP_STREAMING_MEDIA == streamingItem.getMediaType() || MediaType.HTTP_STREAMING_MEDIA_EBD == streamingItem.getMediaType()){
                useHLSDownload = (dbInfo.DlStatus > 0);
            }
            // display associated Subtitle/CC flag or not
            if (null != dbInfo.associatedSubtitleFile || null != dbInfo.associatedTimedTextTrack) {
                subtitleIcon.setVisibility(View.VISIBLE);
            } else {
                subtitleIcon.setVisibility(View.GONE);
            }

            // display resume button or not
            if(dbInfo.lastPlaybackPosInMs > 0 || null != dbInfo.DlLocalServerUrl) {

                resumeButton.setVisibility(View.VISIBLE);
                resumeButton.setFocusable(false);

                final int groupIdForListener = groupPosition;
                final int childIdForListener = childPosition;
                resumeButton.setOnClickListener( new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if(null != resumeButtonListener) {
                            resumeButtonListener.onResumeButtonClick(groupIdForListener, childIdForListener);
                        }
                    }
                });
                resumeButton.clearFocus();
            } else {
                resumeButton.setVisibility(View.GONE);
            }
        } else {
            resumeButton.setVisibility(View.GONE);
            subtitleIcon.setVisibility(View.GONE);
        }


        // set the Secured HLS flag if needed
        ImageView DRMicon = (ImageView)convertView.findViewById(R.id.mediaitem_DRM_img);
        if((null != streamingItem.getBootAddress() && null != streamingItem.getCompanyName()) ||
            null != streamingItem.getDRMLicenseAcquisitionUrl()) {
            DRMicon.setImageResource(R.drawable.secured_httpstr_flag);
            DRMicon.setVisibility(View.VISIBLE);
        } else {
            DRMicon.setVisibility(View.GONE);
        }

        fileNameTxt.setText(streamingItem.getDisplayName());
        fileNameTxt.setTextColor(context.getResources().getColor(R.color.highlight_file));
        hlsDownloadProgress.setVisibility(View.GONE);

        // set item icon and HLS Download progress if need be
        if( useHLSDownload) {

            //Log.d(TAG, "getViewForStreamingItem - useHLSDl " + streamingItem.getMediaUri());
            // if the local url is set, the stream is completely downloaded
            if(DatabaseInfo.DL_STATUS_FULLY_LOCAL == dbInfo.DlStatus) {
                itemIcon.setImageResource(R.drawable.hls_dl_icon_done);
            } else {
                // set icon
                itemIcon.setImageResource(R.drawable.hls_dl_icon);

                hlsDownloadProgress.setMax(dbInfo.mediaDurationInMs);
                // switch between secondary progress and primary progress to differentiate paused and downloading modes
                if( DatabaseInfo.DL_STATUS_DOWNLOADING == dbInfo.DlStatus) {
                    hlsDownloadProgress.setProgress(dbInfo.DLProgress);
                    hlsDownloadProgress.setSecondaryProgress(0);
                } else {
                    hlsDownloadProgress.setProgress(0);
                    hlsDownloadProgress.setSecondaryProgress(dbInfo.DLProgress);
                }
                hlsDownloadProgress.setVisibility(View.VISIBLE);
            }
        } else { // the stream is not in "HLS Download" mode
            if(MediaType.HTTP_STREAMING_MEDIA == streamingItem.getMediaType()) {
                itemIcon.setImageResource(R.drawable.httpstr_icon);
            } else if(MediaType.HTTP_STREAMING_MEDIA_EBD == streamingItem.getMediaType()) {
                itemIcon.setImageResource(R.drawable.httpstr_embedded_icon);
            }
        }
        itemIcon.setVisibility(View.VISIBLE);

        return convertView;
    }



    private View getViewForPlaylistItem(View convertView, ViewGroup parent, StreamingMediaList streamingItem, int groupPosition, int childPosition) {

        Log.i(TAG, "getViewForPlaylistItem");
        if(null != convertView) {
            if(null == convertView.findViewById(R.id.medialist_item_icon) ) {
                convertView = null;
            }
        }
        if(null == convertView) {
            LayoutInflater vi = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.medialist_item, null);
        }

        ImageView itemIcon = (ImageView)convertView.findViewById(R.id.medialist_item_icon);
        TextView fileNameTxt = (TextView)convertView.findViewById(R.id.medialist_item_title_txt);
        ProgressBar hlsDownloadProgress = (ProgressBar)convertView.findViewById(R.id.hls_dl_progress);

        //DatabaseInfo dbInfo = streamingItem.getAssociatedDBInfo();
        boolean useHLSDownload = false;

        ImageView subtitleIcon = (ImageView)convertView.findViewById(R.id.mediaitem_associated_subtitle_img);
        ImageButton resumeButton = (ImageButton)convertView.findViewById(R.id.mediaitem_associated_resume_time);

        resumeButton.setVisibility(View.GONE);
        subtitleIcon.setVisibility(View.GONE);

        // set the Secured HLS flag if needed
        ImageView DRMicon = (ImageView)convertView.findViewById(R.id.mediaitem_DRM_img);
        if((null != streamingItem.getBootAddress() && null != streamingItem.getCompanyName()) ||
            null != streamingItem.getDrmLicenseAcquisitionUrl()) {
            DRMicon.setImageResource(R.drawable.secured_httpstr_flag);
            DRMicon.setVisibility(View.VISIBLE);
        } else {
            DRMicon.setVisibility(View.GONE);
        }

        fileNameTxt.setText(streamingItem.getDisplayName());
        fileNameTxt.setTextColor(context.getResources().getColor(R.color.highlight_file));
        hlsDownloadProgress.setVisibility(View.GONE);

         // the stream is not in "HLS Download" mode
            if(MediaType.MEDIA_PLAYLIST == streamingItem.getMediaType()) {
                itemIcon.setImageResource(R.drawable.httpstr_icon_green);
            }

        itemIcon.setVisibility(View.VISIBLE);

        return convertView;
    }


    private View getViewForLocalFileItem(View convertView, ViewGroup parent, LocalFileMediaItem localItem, int groupPosition, int childPosition) {

        //Log.i(TAG, "getViewForLocalFileItem");
        if(null != convertView) {
            if(null == convertView.findViewById(R.id.medialist_item_icon) ) {
                convertView = null;
            }
        }
        LayoutInflater vi = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = vi.inflate(R.layout.medialist_item, null);

        TextView fileNameTxt = (TextView)convertView.findViewById(R.id.medialist_item_title_txt);
        fileNameTxt.setText(localItem.getDisplayName());

        DatabaseInfo dbInfo = localItem.getAssociatedDBInfo();

        ImageView itemIcon = (ImageView)convertView.findViewById(R.id.medialist_item_icon);
        itemIcon.setVisibility(View.VISIBLE);
        itemIcon.setImageResource(R.drawable.local_media_icon);

        if( null != dbInfo) {
            // CC icon
            if (null != dbInfo.associatedSubtitleFile || null != dbInfo.associatedTimedTextTrack) {
                ImageView subtitleIcon = (ImageView)convertView.findViewById(R.id.mediaitem_associated_subtitle_img);
                subtitleIcon.setVisibility(View.VISIBLE);
            }

            if(dbInfo.lastPlaybackPosInMs > 0) {
                ImageButton resumeButton = (ImageButton)convertView.findViewById(R.id.mediaitem_associated_resume_time);
                resumeButton.setVisibility(View.VISIBLE);
                resumeButton.setFocusable(false);

                final int groupIdForListener = groupPosition;
                final int childIdForListener = childPosition;
                resumeButton.setOnClickListener( new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if(null != resumeButtonListener) {
                            resumeButtonListener.onResumeButtonClick(groupIdForListener, childIdForListener);
                        }
                    }
                });
                resumeButton.clearFocus();
            }
        }

        return convertView;
    }

    public Object getGroup(int groupPosition) {
        return groups.get(groupPosition);
    }

    public int getGroupCount() {
        return groups.size();
    }

    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {

        LayoutInflater vi = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = vi.inflate(R.layout.medialist_header, null);

        TextView textView = (TextView) convertView.findViewById(R.id.medialist_header_title);

        ImageView groupStateIcon = (ImageView)convertView.findViewById(R.id.groupStateImg);
        if(items.get(groupPosition).size() > 0 ) {
            if(isExpanded) {
                groupStateIcon.setImageResource(R.drawable.group_arrow_dwn);
            } else {
                groupStateIcon.setImageResource(R.drawable.group_arrow_right);
            }
            textView.setText(getGroup(groupPosition).toString());
        } else {
            textView.setText(getGroup(groupPosition).toString() + " " + context.getString(R.string.empty_group_addon));
        }
        return convertView;
    }

    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    public boolean hasStableIds() {
        return true;
    }
}
