package com.insidesecure.drm.android.reference.activities;

import java.util.*;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.*;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.*;

import android.util.Log;
import android.view.*;
import android.widget.*;
import com.insidesecure.drm.android.reference.*;
import com.insidesecure.drm.android.reference.xoplayer.R;
import com.insidesecure.drmagent.*;

/**
 * @author
 */
@TargetApi(16)
public class AdvancedPlayActivity extends AbstractDRMActivity implements PopupWindow.OnDismissListener
{
    private static final int ROW_BKGD_COLOR_UNSELECTED = Color.parseColor("#39454c");
    private static final int ROW_BKGD_COLOR_SELECTED = Color.parseColor("#232B2F");

    private PopupWindow mPopupWindow;

    private boolean mSupportsDownloadAndPlay = false;

    private List<DRMContent.VideoQualityLevel> mSelectedVideoQualityLevels = new ArrayList<DRMContent.VideoQualityLevel>();

    private DRMContent.AudioTrack mSelectedAudioTrack;
    private DRMContent.AudioQualityLevel mSelectedAudioQualityLevel;

    private DRMContent.SubtitleTrack mSelectedSubtitleTrack;
    private CheckBox mEnableSideloadedSubtitleCheckbox;
    private boolean mEnableSideloadedSubtitle = false;

    private CheckBox mAudioOnlyVideoQualityLevelCheckBox;
    private CheckBox mEnableOffLineModeCheckbox;
    private CheckBox mEnableClearCacheCheckbox;

    private HDMIControl mSelectedHDMIControl;
    private boolean mEnableDownloadAndPlay = false;

    private Button mDownloadButton;
    private CheckBox mDownloadPlayCheckbox;

    private DRMContent.VideoQualityLevel mSelectedVideoQualityLevel;

    private View.OnClickListener onClickListener;

    private View upButton, downButton;
    private ListView list;
    public MultiSelectionSpinner mAudioTrackMultiSelectionSpinner;
    public MultiSelectionSpinner mSubtitleTrackMultiSelectionSpinner;

    @Override
    protected void onCreate(final Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);

        onClickListener = new View.OnClickListener()
        {


            public void onClick(View view)
            {
                DropDownListAdapter listAdapter;
                Object auxItem;

                listAdapter = (DropDownListAdapter) list.getAdapter();

                if (view == upButton)
                {
                    for (int i = 1; i < listAdapter.getCount(); i++)
                    {
                        if (listAdapter.getItem(i) == mSelectedVideoQualityLevel)
                        {
                            auxItem = listAdapter.getItem(i - 1);
                            listAdapter.remove(auxItem);
                            listAdapter.insert(auxItem, i);
                            listAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < listAdapter.getCount() - 1; i++)
                    {
                        if (listAdapter.getItem(i) == mSelectedVideoQualityLevel)
                        {
                            auxItem = listAdapter.getItem(i);
                            listAdapter.remove(auxItem);
                            listAdapter.insert(auxItem, i + 1);
                            listAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                }
            }
        };

        setContentView(R.layout.advanced_play);
    }

    @Override
    public void onDRMContentInstanceCreatedInternal(final DRMContent drmContent) {

        if (drmContent == null) {
            Log.e(TAG, "Error while opening content, DRMContent is NULL in onDRMContentInstanceCreatedInternal()");
            showGeneralErrorDialog();
            return;
        }

        mSelectedAudioTrack = null;
        mSelectedSubtitleTrack = null;
        mSelectedVideoQualityLevels.clear();
        mSelectedAudioQualityLevel = null;
        mSelectedHDMIControl = null;
        mEnableDownloadAndPlay = false;

        final List<DRMContent.AudioTrack> audioTracks = drmContent.getAudioTracks();
        final boolean haveAudioSelectables = audioTracks.size() > 1;

        final TableRow audioSelectionTextTableRow = (TableRow) findViewById(R.id.audioSelectionTextTableRow);
        audioSelectionTextTableRow.setVisibility(View.GONE);

        final TableRow audioTrackTableRow = (TableRow) findViewById(R.id.audioTrackTableRow);
        audioTrackTableRow.setVisibility(View.GONE);

        final TableRow audioQualityLevelTableRow = (TableRow) findViewById(R.id.audioQualityLevelTableRow);
        audioQualityLevelTableRow.setVisibility(View.GONE);

        final TableRow audioTrackMultiTableRow = (TableRow) findViewById(R.id.audioTrackMultiTableRow);
        audioTrackMultiTableRow.setVisibility(View.GONE);

        if (haveAudioSelectables)
        {
            audioTrackTableRow.setVisibility(View.VISIBLE);

            final ArrayAdapter<CharSequence> audioTrackArrayAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
            final Spinner audioTrackSpinner = (Spinner) findViewById(R.id.audioTrackSpinner);

            mSelectedAudioTrack = audioTracks.get(0);

            List<String> audioTrackStrings = Tools.getAudioTrackStrings(audioTracks);
            audioTrackArrayAdapter.addAll(audioTrackStrings);

            audioTrackArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            audioTrackSpinner.setAdapter(audioTrackArrayAdapter);

            mAudioTrackMultiSelectionSpinner = (MultiSelectionSpinner) findViewById(R.id.audioTrackMultiSelectionSpinner);
            mAudioTrackMultiSelectionSpinner.setAtLeastOneMustBeSelected(true);
            mAudioTrackMultiSelectionSpinner.setItems(audioTrackStrings);

            final Spinner audioQualityLevelSpinner = (Spinner) findViewById(R.id.audioQualityLevelSpinner);
            final ArrayAdapter<CharSequence> audioQualityLevelArrayAdapter = new ArrayAdapter<CharSequence>(AdvancedPlayActivity.this, android.R.layout.simple_spinner_item);
            audioQualityLevelArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            audioQualityLevelSpinner.setAdapter(audioQualityLevelArrayAdapter);

            final List<DRMContent.AudioQualityLevel> audioQualityLevels = mSelectedAudioTrack.getAudioQualityLevels();
            audioQualityLevelSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
            {
                public void onItemSelected(final AdapterView<?> adapterView, final View view, final int position, final long l)
                {
                    mSelectedAudioQualityLevel = audioQualityLevels.get(position);
                }

                public void onNothingSelected(final AdapterView<?> adapterView)
                {
                }
            });

            audioTrackSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
            {
                public void onItemSelected(final AdapterView<?> adapterView, final View view, final int position, final long l)
                {
                    mAudioTrackMultiSelectionSpinner.setSelection(position);

                    mSelectedAudioTrack = audioTracks.get(position);
                    audioQualityLevelTableRow.setVisibility(View.GONE);
                    audioQualityLevelArrayAdapter.clear();
                    final DRMContent.AudioTrack audioTrack = audioTracks.get(position);
                    if (audioTrack.mAudioQualityLevels.size() > 1)
                    {
                        for (DRMContent.AudioQualityLevel audioQualityLevel : audioQualityLevels)
                        {
                            audioQualityLevelArrayAdapter.add("" + audioQualityLevel.mBitRate);
                        }
                        audioQualityLevelArrayAdapter.notifyDataSetChanged();
                        audioQualityLevelTableRow.setVisibility(View.VISIBLE);
                    }
                }

                public void onNothingSelected(final AdapterView<?> adapterView)
                {
                }
            });
        }

        if (haveAudioSelectables)
        {
            audioSelectionTextTableRow.setVisibility(View.VISIBLE);
        }

        boolean haveVideoSelectables = false;

        final TableRow videoSelectionTextTableRow = (TableRow) findViewById(R.id.videoSelectionTextTableRow);
        videoSelectionTextTableRow.setVisibility(View.GONE);

        final TableRow videoQualityLevelTableRow = (TableRow) findViewById(R.id.videoQualityLevelTableRow);
        videoQualityLevelTableRow.setVisibility(View.GONE);
        final List<DRMContent.VideoQualityLevel> videoQualityLevels = drmContent.getVideoQualityLevels();
        final Spinner videoQualityLevelSpinner = (Spinner) findViewById(R.id.videoQualityLevelSpinner);
        if (videoQualityLevels.size() > 1)
        {

            mSelectedVideoQualityLevels.addAll(videoQualityLevels);

            haveVideoSelectables = true;
            videoQualityLevelTableRow.setVisibility(View.VISIBLE);
            videoQualityLevelSpinner.setOnTouchListener(new View.OnTouchListener()
            {
                public boolean onTouch(final View view, final MotionEvent motionEvent)
                {
                    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN)
                    {
                        initiatePopUp(videoQualityLevelSpinner, videoQualityLevels, mSelectedVideoQualityLevels);
                        return true;
                    }
                    return false;
                }
            });
        }

        // For now, just disable the video selector spinner (entire table row)
        final TableRow videoSelectorTableRow = (TableRow) findViewById(R.id.videoSelectorTableRow);
        videoSelectorTableRow.setVisibility(View.GONE);
/*
        final Spinner videoSelectors = (Spinner)findViewById(R.id.videoSelectorSpinner);
        videoSelectors.setOnTouchListener(new View.OnTouchListener()
        {
            public boolean onTouch(final View view, final MotionEvent motionEvent)
            {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN)
                {
                    initiatePopUp(videoSelectors,videoQualityLevels);
                    return true;
                }
                return false;
            }
        });
*/

        if (haveVideoSelectables)
        {
            videoSelectionTextTableRow.setVisibility(View.VISIBLE);
        }

        // It is possible to play *only* the audio-only stream
        final TableRow audioOnlyQualityLevelTableRow = (TableRow) findViewById(R.id.audioOnlyVideoQualityLevelTableRow);
        audioOnlyQualityLevelTableRow.setVisibility(View.GONE);
        if (drmContent.getDRMContentFormat() == DRMContentFormat.SMOOTH_STREAMING && DRMFusionAgentReferenceApplication.sSupportsAudioOnlySmoothStreaming)
        {
            audioOnlyQualityLevelTableRow.setVisibility(View.VISIBLE);
            mAudioOnlyVideoQualityLevelCheckBox = (CheckBox) findViewById(R.id.audioOnlyVideoQualityLevelLabelCheckBox);
            mAudioOnlyVideoQualityLevelCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {

                    videoQualityLevelSpinner.setEnabled(!isChecked);
                    mSelectedVideoQualityLevels.clear();

                    if (isChecked) {
                        mSelectedVideoQualityLevels.add(DRMContent.AUDIO_ONLY_VIDEO_QUALITY_LEVEL);
                    } else {
                        if (videoQualityLevels.size() > 1) {
                            mSelectedVideoQualityLevels.addAll(videoQualityLevels);
                        }
                    }
                }
            });
        }

        final List<DRMContent.SubtitleTrack> subtitleTracks = drmContent.getSubtitleTracks();

        final boolean haveSubtitleSelectables = subtitleTracks.size() > 0;

        // We always show the label - side-loaded subtitles can be used
        final TableRow subtitleSelectionTextTableRow = (TableRow) findViewById(R.id.subtitleSelectionTextTableRow);

        mEnableSideloadedSubtitleCheckbox = (CheckBox) findViewById(R.id.enableSideloadedSubtitlesCheckBox);
        mEnableSideloadedSubtitleCheckbox.setEnabled(true);
        mEnableSideloadedSubtitleCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
        {
            public void onCheckedChanged(final CompoundButton compoundButton, final boolean checked)
            {
                mEnableSideloadedSubtitle = checked;
            }
        });

        final TableRow subtitleTableRow = (TableRow) findViewById(R.id.subtitleSpinnerTableRow);
        subtitleTableRow.setVisibility(View.GONE);

        final TableRow subtitleTrackMultiTableRow = (TableRow) findViewById(R.id.subtitleMultiSelectSpinnerTableRow);
        subtitleTrackMultiTableRow.setVisibility(View.GONE);

        if (haveSubtitleSelectables)
        {
            subtitleTableRow.setVisibility(View.VISIBLE);

            final ArrayAdapter<CharSequence> subtitleTrackArrayAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
            subtitleTrackArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            List<String> subtitleTrackStrings = new ArrayList<String>();
            subtitleTrackStrings.add("None");
            subtitleTrackStrings.addAll(Tools.getSubtitleTracksString(subtitleTracks));
            subtitleTrackArrayAdapter.addAll(subtitleTrackStrings);

            final Spinner subtitleSpinner = (Spinner) findViewById(R.id.subtitleSpinner);
            subtitleSpinner.setAdapter(subtitleTrackArrayAdapter);

            mSubtitleTrackMultiSelectionSpinner = (MultiSelectionSpinner) findViewById(R.id.subtitleTrackMultiSelectionSpinner);
            mSubtitleTrackMultiSelectionSpinner.setAtLeastOneMustBeSelected(true);
            mSubtitleTrackMultiSelectionSpinner.setEnableNoneValue(true);
            mSubtitleTrackMultiSelectionSpinner.setItems(subtitleTrackStrings);

            subtitleSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
            {
                public void onItemSelected(final AdapterView<?> adapterView, final View view, final int position, final long l)
                {
                    if (position == 0)
                    {
                        mSelectedSubtitleTrack = null;
                        mEnableSideloadedSubtitleCheckbox.setEnabled(true);
                    }
                    else {
                        mSelectedSubtitleTrack = subtitleTracks.get(position - 1);

                        mEnableSideloadedSubtitleCheckbox.setEnabled(false);
                    }
                    mSubtitleTrackMultiSelectionSpinner.setSelection(position);
                }

                public void onNothingSelected(final AdapterView<?> adapterView)
                {
                }
            });
        }


        if (haveSubtitleSelectables)
        {
            subtitleSelectionTextTableRow.setVisibility(View.VISIBLE);
        }

        final TableRow downloadAndPlayTextTableRow = (TableRow) findViewById(R.id.downloadPlayTextTableRow);
        downloadAndPlayTextTableRow.setVisibility(View.GONE);

        final TableRow enableDownloadAndPlayTableRow = (TableRow) findViewById(R.id.enableDownloadAndPlayTableRow);
        enableDownloadAndPlayTableRow.setVisibility(View.GONE);

        mDownloadPlayCheckbox = (CheckBox) findViewById(R.id.enableDownloadAndPlayCheckBox);
        mDownloadPlayCheckbox.setEnabled(false);

        mSupportsDownloadAndPlay = supportsDownloadAndPlay(drmContent);

        if (mSupportsDownloadAndPlay)
        {
            switch (drmContent.getDRMContentFormat())
            {
                default:

                    downloadAndPlayTextTableRow.setVisibility(View.VISIBLE);
                    enableDownloadAndPlayTableRow.setVisibility(View.VISIBLE);
                    mDownloadPlayCheckbox.setEnabled(true);

                    mDownloadPlayCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
                    {
                        public void onCheckedChanged(final CompoundButton compoundButton, final boolean checked)
                        {
                            mEnableDownloadAndPlay = checked;
                            if (haveAudioSelectables)
                            {
                                if (checked)
                                {
                                    // Change the audio tracks selected to a multi-select list ...
                                    audioTrackMultiTableRow.setVisibility(View.VISIBLE);
                                    audioTrackTableRow.setVisibility(View.GONE);
                                }
                                else
                                {
                                    // Change the audio track to be from the single select list
                                    audioTrackMultiTableRow.setVisibility(View.GONE);
                                    audioTrackTableRow.setVisibility(View.VISIBLE);
                                }
                            }
                            if (haveSubtitleSelectables)
                            {
                                if (checked)
                                {
                                    subtitleTrackMultiTableRow.setVisibility(View.VISIBLE);
                                    subtitleTableRow.setVisibility(View.GONE);

                                }
                                else
                                {
                                    subtitleTrackMultiTableRow.setVisibility(View.GONE);
                                    subtitleTableRow.setVisibility(View.VISIBLE);
                                }
                            }

                            if(checked) {
                                getCacheInfoAndUpdateUIAsyncIfNeeded(drmContent);
                            }

                        }

                    });
            }
        }

        boolean haveMiscellaneousSelectables = false;
        final TableRow miscellaneousTextTableRow = (TableRow) findViewById(R.id.miscellaneousTextTableRow);
        miscellaneousTextTableRow.setVisibility(View.GONE);

        if (drmContent.isProtected())
        {
            haveMiscellaneousSelectables = true;

            final Spinner hdmiControlSpinner = (Spinner) findViewById(R.id.hdmiControlSpinner);

            hdmiControlSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
            {
                public void onItemSelected(final AdapterView<?> adapterView, final View view, final int position, final long l)
                {
                    mSelectedHDMIControl = HDMIControl.values()[position];
                }

                public void onNothingSelected(final AdapterView<?> adapterView)
                {
                }
            });
        }
        else
        {
            findViewById(R.id.hdmiControlTableRow).setVisibility(View.GONE);
        }

        if (haveMiscellaneousSelectables)
        {
            miscellaneousTextTableRow.setVisibility(View.VISIBLE);
        }

        mEnableOffLineModeCheckbox = (CheckBox) findViewById(R.id.enableOfflineModeCheckBox);
        mEnableOffLineModeCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
                mDownloadButton.setVisibility(mSupportsDownloadAndPlay && !isChecked? View.VISIBLE : View.GONE);
            }
        });

        mEnableClearCacheCheckbox = (CheckBox) findViewById(R.id.enableClearCacheCheckBox);

        Button playButton = (Button) findViewById(R.id.playButton);
        playButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(final View view) {
                if (mEnableClearCacheCheckbox.isChecked()) {
                    Log.d(TAG, "Clearing of Cached data for Content: " + getDRMContent().getOriginalContentURI());
                    getDRMContent().clearCachedData();
                }

                // Of we go!!
                initiatePlayback(getIntent());
            }
        });

        mDownloadButton = (Button) findViewById(R.id.downloadButton);
        mDownloadButton.setVisibility(View.GONE);

        if (mSupportsDownloadAndPlay && !getDRMAgent().getDRMAgentConfiguration().isOfflineMode())
        {
            mDownloadButton.setVisibility(View.VISIBLE);

            mDownloadButton.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(final View view) {

                    if (mEnableClearCacheCheckbox.isChecked()) {
                        Log.d(TAG, "Clearing of Cached data for Content: " + getDRMContent().getOriginalContentURI());
                        getDRMContent().clearCachedData();
                    }

                    // Of we go!!
                    initiateDownload();
                    finish();
                }
            });

            if (mDownloadServiceBound)
            {
                final boolean activelyDownloading = mDownloadService.isActivelyDownloading();
                mDownloadButton.setEnabled(!activelyDownloading);
                mDownloadPlayCheckbox.setEnabled(!activelyDownloading);
            }
        }

        // Finally, dismiss three loading spinner
        dismissLoadingDialog();

    }

    private void getCacheInfoAndUpdateUIAsyncIfNeeded(final DRMContent drmContent)
    {
        new AsyncTask<Void, Void, DRMCacheInfo>()
        {
            private ProgressDialog mProgressDialog;

            @Override
            protected void onPostExecute(DRMCacheInfo drmCacheInfo) {
                mProgressDialog.dismiss();
                mProgressDialog = null;

                if (drmCacheInfo != null) {

                    if (mAudioOnlyVideoQualityLevelCheckBox != null)
                    {
                        mAudioOnlyVideoQualityLevelCheckBox.setChecked(false);
                    }

                    mSelectedVideoQualityLevel = drmCacheInfo.getCachedVideoQualityLevel();
                    mSelectedVideoQualityLevels.clear();
                    mSelectedVideoQualityLevels.add(drmCacheInfo.getCachedVideoQualityLevel());

                    if (drmContent.getAudioTracks().size() > 1) {
                        mAudioTrackMultiSelectionSpinner.setSelection(Tools.getAudioTrackStrings(drmCacheInfo.getCachedAudioTracks()));
                    }
                    if (drmContent.getSubtitleTracks().size() > 0 && !drmCacheInfo.getCachedSubtitleTracks().isEmpty()) {
                        mSubtitleTrackMultiSelectionSpinner.setSelection(Tools.getSubtitleTracksString(drmCacheInfo.getCachedSubtitleTracks()));
                    }
                }
            }

            @Override
            protected DRMCacheInfo doInBackground(Void... voids) {

                if (getDRMAgent().getDownloadManager().getCacheState(drmContent.getOriginalContentURI()) != DRMCacheState.NONE) {
                    return getDRMAgent().getDownloadManager().retrieveDRMCacheInfo(drmContent.getOriginalContentURI());
                } else {
                    return null;
                }
            }

            @Override
            protected void onPreExecute() {
                mProgressDialog = new ProgressDialog(AdvancedPlayActivity.this);
                mProgressDialog.setMessage("Loading cache info...");
                mProgressDialog.setCancelable(false);
                mProgressDialog.setIndeterminate(true);
                mProgressDialog.show();
            }
        }.execute();
    }

    private void showGeneralErrorDialog(){
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle(getText(R.string.dialog_title));
        alertDialog.setMessage(getText(R.string.dialog_text_general_drm_error));
        alertDialog.setCancelable(false);
        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getText(R.string.dialog_button_ok),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
        alertDialog.show();
    }

    private boolean supportsDownloadAndPlay(final DRMContent drmContent)
    {
        switch (drmContent.getDRMContentFormat())
        {
            case PIFF:
            case HTTP_LIVE_STREAMING:
            case SMOOTH_STREAMING:
            case MPEG_DASH:
                if (drmContent.getOriginalContentURI().getScheme().startsWith("http") && !drmContent.isLive())
                {
                    return true;
                }
                break;
            default:
                break;
        }
        return false;
    }

    private void initiateDownload()
    {
        if (!mEnableDownloadAndPlay)
        {
            Toast.makeText(AdvancedPlayActivity.this,"Download & Play initiated but download is not enabled",8000).show();
            return;
        }

        final DRMContent drmContent = getDRMContent();

        final List<DRMContent.VideoQualityLevel> videoQualityLevels = drmContent.getVideoQualityLevels();

        DRMContent.VideoQualityLevel videoQualityLevel = null;
        if (!videoQualityLevels.isEmpty())
        {
            videoQualityLevel = videoQualityLevels.get(0);
        }

        if (mSelectedVideoQualityLevels != null && !mSelectedVideoQualityLevels.isEmpty())
        {
            videoQualityLevel = mSelectedVideoQualityLevels.get(0);
        }

        List<DRMContent.AudioTrack> audioTracks = drmContent.getAudioTracks();
        if (mAudioTrackMultiSelectionSpinner != null)
        {
            final List<Integer> selectedIndicies = mAudioTrackMultiSelectionSpinner.getSelectedIndicies();
            if (selectedIndicies.size() > 0)
            {
                List<DRMContent.AudioTrack> selectedAudioTracks = new ArrayList<DRMContent.AudioTrack>();
                for (Integer selectedIndicy : selectedIndicies)
                {
                    selectedAudioTracks.add(audioTracks.get(selectedIndicy));
                }
                audioTracks = selectedAudioTracks;
            }
        }

        List<DRMContent.SubtitleTrack> subtitleTracks = drmContent.getSubtitleTracks();
        if (mSubtitleTrackMultiSelectionSpinner != null)
        {
            final List<Integer> selectedIndicies = mSubtitleTrackMultiSelectionSpinner.getSelectedIndicies();
            if (selectedIndicies.size() > 0)
            {
                List<DRMContent.SubtitleTrack> selectedSubtitleTracks = new ArrayList<DRMContent.SubtitleTrack>();
                for (Integer selectedIndex : selectedIndicies)
                {
                    if (selectedIndex == 0)
                    {
                        // We always ignore the "NONE" in this calculation
                        continue;
                    }

                    selectedSubtitleTracks.add(subtitleTracks.get(selectedIndex - 1));
                }
                subtitleTracks = selectedSubtitleTracks;
            }
            else
            {
                subtitleTracks.clear();
            }
        }
        else
        {
            subtitleTracks.clear();
        }

        mDownloadService.initiateDownload(drmContent.getOriginalContentURI(), drmContent.getDRMContentFormat(), drmContent.getDRMScheme(), videoQualityLevel, audioTracks, subtitleTracks);
    }

    private void initiatePlayback(final Intent intent)
    {
        final Intent firingIntent = new Intent(getBaseContext(), LicenseAcquisitionActivity.class);

        final PlaybackInfo playbackInfo = new PlaybackInfo(getPlaybackInfo());
        playbackInfo.mDownloadAndPlay = mEnableDownloadAndPlay;

        firingIntent.putExtra(Constants.INTENT_EXTRA_CONTENT_PLAYBACK_INFO, playbackInfo);

        if (!mSelectedVideoQualityLevels.isEmpty())
        {
            playbackInfo.mEnabledVideoTracks = mSelectedVideoQualityLevels;
        }

        if (mEnableDownloadAndPlay)
        {
            if (mAudioTrackMultiSelectionSpinner != null)
            {
                final List<Integer> selectedIndicies = mAudioTrackMultiSelectionSpinner.getSelectedIndicies();
                if (selectedIndicies.size() > 0)
                {
                    final List<DRMContent.AudioTrack> selectedAudioTracks = new ArrayList<DRMContent.AudioTrack>();
                    final List<DRMContent.AudioTrack> audioTracks = getDRMContent().getAudioTracks();
                    for (Integer selectedIndicy : selectedIndicies)
                    {
                        selectedAudioTracks.add(audioTracks.get(selectedIndicy));
                    }
                    playbackInfo.mEnabledAudioTracks = selectedAudioTracks;
                    playbackInfo.mEnabledAudioTrack = selectedAudioTracks.get(0);
                }
            }
        }
        else
        {
            if (mSelectedAudioTrack != null)
            {
                playbackInfo.mEnabledAudioTrack = mSelectedAudioTrack;
            }
        }

        if (mSelectedAudioQualityLevel != null)
        {
            playbackInfo.mEnabledAudioTrackQualityLevel = mSelectedAudioQualityLevel;
        }

        if (mSelectedHDMIControl != null)
        {
            playbackInfo.mEnabledHDMIControl = mSelectedHDMIControl;
        }

        if (mEnableDownloadAndPlay)
        {
            if (mSubtitleTrackMultiSelectionSpinner != null)
            {
                final List<Integer> selectedIndicies = mSubtitleTrackMultiSelectionSpinner.getSelectedIndicies();
                List<DRMContent.SubtitleTrack> selectedSubtitleTracks = new ArrayList<DRMContent.SubtitleTrack>();
                List<DRMContent.SubtitleTrack> subtitleTracks = getDRMContent().getSubtitleTracks();
                if (selectedIndicies.size() > 0)
                {
                    for (Integer selectedIndex : selectedIndicies) {
                        if (selectedIndex == 0)
                        {
                            // We always ignore the "NONE" in this calculation
                            continue;
                        }
                        selectedSubtitleTracks.add(subtitleTracks.get(selectedIndex - 1));
                    }
                }
                playbackInfo.mEnabledSubtitleTracks = (ArrayList<DRMContent.SubtitleTrack>)selectedSubtitleTracks;
                if (selectedSubtitleTracks.size() > 0)
                {
                    playbackInfo.mEnabledSubtitleTrack = selectedSubtitleTracks.get(0);
                }
            }
        }
        else
        {
            if (mSelectedSubtitleTrack != null)
            {
                playbackInfo.mEnabledSubtitleTrack = mSelectedSubtitleTrack;
            }
        }

        if (mEnableSideloadedSubtitleCheckbox.isEnabled() && mEnableSideloadedSubtitle)
        {
            playbackInfo.mEnabledSideloadedSubtitles = mEnableSideloadedSubtitle;
        }

        playbackInfo.mOfflineMode = mEnableOffLineModeCheckbox.isChecked();

        startActivity(firingIntent);

        finish();

    }


    public void onDismiss()
    {
        final ListView list = (ListView) mPopupWindow.getContentView().findViewById(R.id.dropDownList);
        DropDownListAdapter dropDownListAdapter = (DropDownListAdapter) list.getAdapter();

/*
        if (!dropDownListAdapter.mSelectedVideoQualityLevels.isEmpty())
        {
            mSelectedVideoQualityLevels.clear();

            for (int i = 0;
                 i < dropDownListAdapter.getCount();
                 i ++)
            {
                if (dropDownListAdapter.mSelectedVideoQualityLevels.contains(dropDownListAdapter.getItem(i)))
                {
                    mSelectedVideoQualityLevels.add((DRMContent.VideoQualityLevel) dropDownListAdapter.getItem(i));
                }
            }
        }
*/
    }

    /*
    * Function to set up the pop-up window which acts as drop-down list
    * */
    private void initiatePopUp(final View layoutBy, final List<DRMContent.VideoQualityLevel> items, final List<DRMContent.VideoQualityLevel> selectedItems)
    {
        final LayoutInflater inflater = (LayoutInflater) AdvancedPlayActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        //get the pop-up window i.e. drop-down layout
        RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.video_quality_select_popup, (ViewGroup) findViewById(R.id.popUpView));

        mPopupWindow = new PopupWindow(layout, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        //Pop-up window background cannot be null if we want the pop-up to listen touch events outside its window
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setTouchable(true);

        //let pop-up be informed about touch events outside its window. This should be done before setting the content of pop-up
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

        //dismiss the pop-up i.e. drop-down when touched anywhere outside the pop-up
        mPopupWindow.setTouchInterceptor(new View.OnTouchListener()
        {
            public boolean onTouch(View v, MotionEvent event)
            {
                // TODO Auto-generated method stub
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE)
                {
                    mPopupWindow.dismiss();
                    return true;
                }
                return false;
            }
        });

        //provide the source layout for drop-down
        mPopupWindow.setContentView(layout);

        mPopupWindow.showAsDropDown(layoutBy);

        mPopupWindow.setOnDismissListener(this);

        //set-up buttons
        upButton = mPopupWindow.getContentView().findViewById(R.id.btnMoveUp);
        upButton.setOnClickListener(onClickListener);
        upButton.setEnabled(false);

        downButton = mPopupWindow.getContentView().findViewById(R.id.btnMoveDown);
        downButton.setOnClickListener(onClickListener);
        downButton.setEnabled(false);

        mSelectedVideoQualityLevel = null;

        //populate the drop-down list
        list = (ListView) mPopupWindow.getContentView().findViewById(R.id.dropDownList);
        final DropDownListAdapter adapter = new DropDownListAdapter(items, selectedItems);
        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {


            public void onItemClick(AdapterView<?> adapterView,
                                    View view,
                                    int i,
                                    long l)
            {
                DropDownListAdapter listAdapter = (DropDownListAdapter) adapterView.getAdapter();

                mSelectedVideoQualityLevel = (DRMContent.VideoQualityLevel) listAdapter.getItem(i);

                upButton.setEnabled(true);
                downButton.setEnabled(true);

                listAdapter.notifyDataSetChanged();
            }
        });

        CheckBox toggleAllCheckBox = (CheckBox) mPopupWindow.getContentView().findViewById(R.id.toggleAllCheckBox);
        toggleAllCheckBox.setChecked(selectedItems.containsAll(items));
        toggleAllCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
        {
            public void onCheckedChanged(final CompoundButton compoundButton, final boolean checked)
            {
                selectedItems.clear();
                if (checked)
                {
                    selectedItems.addAll(items);
                }
                adapter.notifyDataSetChanged();
            }
        });


    }

    public class DropDownListAdapter extends ArrayAdapter
    {
        private List<DRMContent.VideoQualityLevel> mAvailableVideoQualityLevels;
        //private List<DRMContent.VideoQualityLevel> mSelectedVideoQualityLevels;

        public DropDownListAdapter(List<DRMContent.VideoQualityLevel> items, List<DRMContent.VideoQualityLevel> selectedItems)
        {
            super(AdvancedPlayActivity.this, -1, items);

            mAvailableVideoQualityLevels = items;
            mSelectedVideoQualityLevels = selectedItems;
        }

        public int getCount()
        {
            return mAvailableVideoQualityLevels.size();
        }

        public Object getItem(int arg0)
        {
            // TODO Auto-generated method stub
            return mAvailableVideoQualityLevels.get(arg0);
        }

        public long getItemId(int arg0)
        {
            // TODO Auto-generated method stub
            return 0;
        }

        public View getView(int position, View convertView, ViewGroup parent)
        {
            // TODO Auto-generated method stub

            final DRMContent.VideoQualityLevel videoQualityLevel = mAvailableVideoQualityLevels.get(position);

            final ViewHolder holder;
            if (convertView == null)
            {
                final LayoutInflater li = getLayoutInflater();

                convertView = li.inflate(R.layout.video_quality_select_popup_item, null);
                holder = new ViewHolder();
                holder.tv1 = (TextView) convertView.findViewById(R.id.bitrate_text_info_1);
                holder.tv2 = (TextView) convertView.findViewById(R.id.bitrate_text_info_2);
                holder.chkbox = (CheckBox) convertView.findViewById(R.id.bitrate_selected_checkbox);

                convertView.setTag(holder);
            }
            else
            {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.chkbox.setChecked(false);
            if (mSelectedVideoQualityLevels.contains(videoQualityLevel))
            {
                holder.chkbox.setChecked(true);
            }

            holder.tv1.setText(makeBitrateText(videoQualityLevel));
            holder.tv2.setText(makeVideoProfileText(videoQualityLevel));

            holder.chkbox.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(final View view)
                {

                    boolean selected = mSelectedVideoQualityLevels.contains(videoQualityLevel);
                    if (selected)
                    {
                        // Means we are de-selecting the item
                        mSelectedVideoQualityLevels.remove(videoQualityLevel);
                    }
                    else
                    {
                        mSelectedVideoQualityLevels.add(videoQualityLevel);
                    }
                    notifyDataSetChanged();
                }
            });

            convertView.setBackgroundColor(videoQualityLevel == mSelectedVideoQualityLevel ? ROW_BKGD_COLOR_SELECTED : ROW_BKGD_COLOR_UNSELECTED);

            return convertView;
        }

        private String makeBitrateText(final DRMContent.VideoQualityLevel videoQualityLevel)
        {
            if (videoQualityLevel == DRMContent.AUDIO_ONLY_VIDEO_QUALITY_LEVEL)
            {
                return "Audio Only";
            }
            return "" + videoQualityLevel.mBitRate;
        }

        private String makeVideoProfileText(final DRMContent.VideoQualityLevel videoQualityLevel)
        {
            return videoQualityLevel.mVideoProfile + " / " + videoQualityLevel.mVideoProfileLevel;
        }


        private class ViewHolder
        {
            TextView tv1;
            TextView tv2;
            CheckBox chkbox;
        }
    }

    @Override
    protected void downloadServiceConnected()
    {
        if (!mDownloadService.isActivelyDownloading())
        {
            if (mDownloadPlayCheckbox != null)
            {
                mDownloadPlayCheckbox.setEnabled(true);
            }
            if (mDownloadButton != null)
            {
                mDownloadButton.setEnabled(true);
            }
        }
    }
}
