<commit_before>package org.edx.mobile.player;

import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import org.edx.mobile.R;
import org.edx.mobile.base.BaseFragmentActivity;
import org.edx.mobile.http.Api;
import org.edx.mobile.interfaces.SectionItemInterface;
import org.edx.mobile.logger.Logger;
import org.edx.mobile.model.api.EnrolledCoursesResponse;
import org.edx.mobile.model.api.LectureModel;
import org.edx.mobile.model.api.ProfileModel;
import org.edx.mobile.model.api.VideoResponseModel;
import org.edx.mobile.model.db.DownloadEntry;
import org.edx.mobile.module.analytics.ISegment;
import org.edx.mobile.module.analytics.SegmentFactory;
import org.edx.mobile.module.db.DataCallback;
import org.edx.mobile.module.db.IDatabase;
import org.edx.mobile.module.db.impl.DatabaseFactory;
import org.edx.mobile.module.prefs.PrefManager;
import org.edx.mobile.module.prefs.UserPrefs;
import org.edx.mobile.module.storage.IStorage;
import org.edx.mobile.module.storage.Storage;
import org.edx.mobile.task.CircularProgressTask;
import org.edx.mobile.util.AppConstants;
import org.edx.mobile.util.BrowserUtil;
import org.edx.mobile.util.MediaConsentUtils;
import org.edx.mobile.util.MemoryUtil;
import org.edx.mobile.util.NetworkUtil;
import org.edx.mobile.view.VideoListActivity;
import org.edx.mobile.view.adapters.MyAllVideoAdapter;
import org.edx.mobile.view.adapters.OfflineVideoAdapter;
import org.edx.mobile.view.adapters.OnlineVideoAdapter;
import org.edx.mobile.view.adapters.VideoBaseAdapter;
import org.edx.mobile.view.custom.ProgressWheel;
import org.edx.mobile.view.dialog.DeleteVideoDialogFragment;
import org.edx.mobile.view.dialog.IDialogCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class VideoListFragment extends Fragment {

    public static View offlineBar;
    private boolean isLandscape = false;
    private VideoBaseAdapter<SectionItemInterface> adapter;
    private ListView videoListView;
    private boolean myVideosFlag = false;
    private boolean isActivityStarted;
    protected IDatabase db;
    protected IStorage storage;
    private static final int MSG_UPDATE_PROGRESS = 1022;
    private DeleteVideoDialogFragment confirmDeleteFragment, downloadSizeExceedDialog;
    private String openInBrowserUrl;
    private String chapterName;
    private LectureModel lecture;
    private EnrolledCoursesResponse enrollment;
    private int playingVideoIndex = -1;
    private VideoListCallback callback;
    private DownloadEntry videoModel;
    private boolean downloadAvailable = false;
    private Button deleteButton;
    private ISegment segIO;
    private Api api;
    private final Logger logger = new Logger(getClass().getName());

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        initDB();
        segIO = SegmentFactory.getInstance();
        api = new Api(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return inflater.inflate(R.layout.fragment_video_list, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        restore(savedInstanceState);

        Intent extraIntent = getActivity().getIntent();
        if(extraIntent!=null){
            if (extraIntent.hasExtra("FromMyVideos")) {
                myVideosFlag = extraIntent.getBooleanExtra(
                        "FromMyVideos", false);
            }

            // read incoming chapter name
            if (chapterName == null) {
                chapterName = extraIntent.getStringExtra("chapter");
            }

            // read incoming lecture model
            if (lecture == null) {
                lecture = (LectureModel) extraIntent
                        .getSerializableExtra("lecture");
            }
            // read incoming enrollment model
            if (enrollment == null) {
                enrollment = (EnrolledCoursesResponse) extraIntent
                        .getSerializableExtra(BaseFragmentActivity.EXTRA_ENROLLMENT);
            }
        }

        if (chapterName == null) {
            if (enrollment != null && lecture != null) {
                if (lecture.chapter != null) {
                    chapterName = lecture.chapter.chapter;
                }
            }
        }

        videoListView = (ListView) getView().findViewById(R.id.list_video);

        if (videoListView != null) {
            isLandscape = false;

            videoListView.setEmptyView(getView().findViewById(
                    R.id.empty_list_view));
            offlineBar = (View) getView().findViewById(R.id.offline_bar);

            if (!(NetworkUtil.isConnected(getActivity()))) {
                if (offlineBar != null)
                    offlineBar.setVisibility(View.VISIBLE);
                showDeletePanel(getView());
                AppConstants.offline_flag = true;
            } else {
                if (offlineBar != null) {
                    offlineBar.setVisibility(View.GONE);
                }
                AppConstants.offline_flag = false;
            }

            setAdaptertoVideoList();

        } else {
            isLandscape = true;
            // probably the landscape player view, so hide action bar
            ActionBar bar = getActivity().getActionBar();
            if(bar!=null){
                bar.hide();
            }
        }
    }

    public void setAdaptertoVideoList(){
        if (!myVideosFlag) {
            if (AppConstants.offline_flag) {
                addDataToOfflineAdapter();
            } else {
                addDataToOnlineAdapter();
            }
        } else {
            showDeletePanel(getView());
            hideOpenInBrowserPanel();
            addDataToMyVideoAdapter();
        }
    }
    
    
    private void addDataToOnlineAdapter() {
        try {
            String selectedId = null;
            if(adapter!=null){
                selectedId = adapter.getVideoId();
            }
            adapter = new OnlineVideoAdapter(getActivity(), db , storage) {
                @Override
                public void onItemClicked(final SectionItemInterface model, final int position) {
                    if (model.isDownload()) {
                        // hide delete panel first, so that multiple-tap is blocked
                        hideDeletePanel(VideoListFragment.this.getView());

                        if (!NetworkUtil.isConnected(getContext())) {
                            ((VideoListActivity) getActivity()).showInfoMessage(getString(R.string.need_data));
                            notifyAdapter();
                        } else {
                            IDialogCallback dialogCallback = new IDialogCallback() {
                                @Override
                                public void onPositiveClicked() {
                                    startOnlinePlay(model, position);
                                }

                                @Override
                                public void onNegativeClicked() {
                                    //
                                }
                            };
                            MediaConsentUtils.consentToMediaDownload(getActivity(), dialogCallback);
                        }
                    }
                }

                @Override
                public void download(final DownloadEntry videoData, final ProgressWheel progressWheel) {
                    try {
                        if (!NetworkUtil.isConnected(getContext())) {
                            ((VideoListActivity) getActivity()).showInfoMessage(getString(R.string.need_data));
                            notifyAdapter();
                        } else {
                            if (!(getActivity() instanceof VideoListActivity)) {
                                return;
                            }
                            IDialogCallback dialogCallback = new IDialogCallback() {
                                @Override
                                public void onPositiveClicked() {
                                    startOnlineDownload(videoData, progressWheel);
                                }

                                @Override
                                public void onNegativeClicked() {
                                    //
                                }
                            };
                            MediaConsentUtils.consentToMediaDownload(getActivity(), dialogCallback);
                        }

                    } catch (Exception e) {
                        logger.error(e);
                    }
                }
            };

            if(selectedId!=null){
                adapter.setVideoId(selectedId);
            }
            videoListView.setAdapter(adapter);
            videoListView.setOnItemClickListener(adapter);

            if (lecture != null) {
                setActivityTitle(lecture.name);
                for (VideoResponseModel m : lecture.videos) {
                    if (openInBrowserUrl == null
                            || openInBrowserUrl.equalsIgnoreCase("")) {
                        openInBrowserUrl = m.section_url;
                    }
                    final DownloadEntry downloadEntry = (DownloadEntry) storage
                            .getDownloadEntryfromVideoResponseModel(m);
                    adapter.add(downloadEntry);
                }

            } else {
                setActivityTitle(chapterName);

                ArrayList<SectionItemInterface> list = api
                        .getLiveOrganizedVideosByChapter(enrollment.getCourse()
                                .getId(), chapterName);
                for (SectionItemInterface m : list) {
                    if (m.isVideo()) {
                        VideoResponseModel vidmodel = (VideoResponseModel) m;
                        DownloadEntry downloadEntry = (DownloadEntry) storage
                                .getDownloadEntryfromVideoResponseModel(vidmodel);
                        adapter.add(downloadEntry);
                    } else {
                        adapter.add(m);
                    }
                }
            }
            adapter.setSelectedPosition(playingVideoIndex);
            adapter.notifyDataSetChanged();
        } catch (Exception e) {
            logger.error(e);
        }
    }

    private void startOnlinePlay(SectionItemInterface model, int position){
        // hide delete panel first, so that multiple-tap is blocked
        hideDeletePanel(VideoListFragment.this.getView());

        if ( !isPlayerVisible()) {
            // don't try to showPlayer() if already shown here
            // this will cause player to freeze
            showPlayer();
        }

        DownloadEntry de = (DownloadEntry) model;
        addVideoDatatoDb(de);
        adapter.setVideoId(de.videoId);

        // initialize index for this model
        playingVideoIndex = position;

        play(model);
        notifyAdapter();
    }


    private void startOnlineDownload(DownloadEntry videoData, ProgressWheel progressWheel){
        long downloadSize = videoData.size;
        if (downloadSize > MemoryUtil
                .getAvailableExternalMemory(getActivity())) {
            ((VideoListActivity) getActivity())
                    .showInfoMessage(getString(R.string.file_size_exceeded));
            notifyAdapter();
        } else {
            if (downloadSize < MemoryUtil.GB) {
                startDownload(videoData, progressWheel);
            } else {
                showStartDownloadDialog(videoData, progressWheel);
            }
        }
    }

    private void addDataToOfflineAdapter() {
        try {
            String selectedId = null;
            if(adapter!=null){
                selectedId = adapter.getVideoId();
            }
            adapter = new OfflineVideoAdapter(getActivity(), db) {
                @Override
                public void onItemClicked(SectionItemInterface model,
                        int position) {
                    if (model.isDownload()) {

                        DownloadEntry downloadEntry = (DownloadEntry) model;
                        if (downloadEntry.isDownloaded()) {
                            adapter.setVideoId(downloadEntry.videoId);
                            // hide delete panel first, so that multiple-tap is blocked
                            hideDeletePanel(VideoListFragment.this.getView());

                            showPlayer();
                            // initialize index for this model
                            playingVideoIndex = position;

                            play(model);
                            notifyAdapter();
                        } else {
                            ((VideoListActivity) getActivity())
                                    .showOfflineAccessMessage();
                        }
                    }
                }

                @Override
                public void onSelectItem() {
                    handleCheckboxSelection();
                }
            };
            if(selectedId!=null){
                adapter.setVideoId(selectedId);
            }
            videoListView.setAdapter(adapter);
            videoListView.setOnItemClickListener(adapter);

            setActivityTitle(chapterName);

            ArrayList<SectionItemInterface> list = api
                    .getLiveOrganizedVideosByChapter(enrollment.getCourse()
                            .getId(), chapterName);
            downloadAvailable = false;
            for (SectionItemInterface m : list) {
                if (m.isVideo()) {
                    VideoResponseModel vidmodel = (VideoResponseModel) m;
                    DownloadEntry downloadEntry = (DownloadEntry) storage
                            .getDownloadEntryfromVideoResponseModel(vidmodel);
                    adapter.add(downloadEntry);
                    if(downloadEntry.isDownloaded()){
                        downloadAvailable = true;
                    }
                    // adapx.add(downloadEntry);
                } else {
                    adapter.add(m);
                    // adapx.add(m);
                }
            }

            if(!downloadAvailable){
                hideDeletePanel(getView());
            }

            adapter.setSelectedPosition(playingVideoIndex);
            adapter.notifyDataSetChanged();
        } catch (Exception e) {
            logger.error(e);
        }

    }

    private void addDataToMyVideoAdapter() {
        try {
            String selectedId = null;
            if(adapter!=null){
                selectedId = adapter.getVideoId();
            }

            adapter = new MyAllVideoAdapter(getActivity(), db) {
                @Override
                public void onItemClicked(SectionItemInterface model,
                        int position) {
                    if (!AppConstants.myVideosDeleteMode) {
                        if (model.isDownload()) {
                            DownloadEntry downloadEntry = (DownloadEntry) model;
                            if (downloadEntry.isDownloaded()) {
                                adapter.setVideoId(downloadEntry.videoId);
                                // hide delete panel first, so that multiple-tap is blocked
                                hideDeletePanel(VideoListFragment.this.getView());
                                showPlayer();

                                // initialize index for this model
                                playingVideoIndex = position;
                                play(model);
                                notifyAdapter();
                            }
                        }
                    }
                }

                @Override
                public void onSelectItem() {
                    handleCheckboxSelection();
                }
            };
            if(selectedId!=null){
                adapter.setVideoId(selectedId);
            }

            videoListView.setAdapter(adapter);
            videoListView.setOnItemClickListener(adapter);

            setActivityTitle(enrollment.getCourse().getName());
            try{
                segIO.screenViewsTracking("My Videos - All Videos - "
                        + enrollment.getCourse().getName());
            }catch(Exception e){
                logger.error(e);
            }

            ArrayList<SectionItemInterface> list = storage
                    .getSortedOrganizedVideosByCourse(enrollment.getCourse().getId());
            downloadAvailable = false;
            if(list==null||list.size()==0){
                hideDeletePanel(getView());
                downloadAvailable = false;
            }else{
                downloadAvailable = true;
            }

            for (SectionItemInterface m : list) {
                adapter.add(m);
            }
            notifyAdapter();
        } catch (Exception e) {
            logger.error(e);
        }
    }

    /**
     * This function sets text to the title in Action Bar
     * @param title
     */
    private void setActivityTitle(String title){
        try{
            getActivity().setTitle(title);
        }catch(Exception e){
            logger.error(e);
        }
    }

    private void play(SectionItemInterface model) {
        if (model instanceof DownloadEntry) {
            hideOpenInBrowserPanel();

            DownloadEntry v = (DownloadEntry) model;
            try {
                String prefName = PrefManager.getPrefNameForLastAccessedBy(getProfile()
                        .username, v.eid);
                PrefManager prefManager = new PrefManager(getActivity(), prefName);
                VideoResponseModel vrm = api.getVideoById(v.eid, v.videoId);
                prefManager.putLastAccessedSubsection(vrm.getSection().id, false);

                // capture chapter name
                if (chapterName == null) {
                    // capture the chapter name of this video
                    chapterName = v.chapter;
                }

                if (callback != null) {
                    videoModel = v;
                    callback.playVideoModel(v);
                    adapter.setVideoId(videoModel.videoId);
                    adapter.setSelectedPosition(playingVideoIndex);
                    adapter.notifyDataSetChanged();
                }
            } catch (Exception e) {
                logger.error(e);
            }

        }
    }

    private void showPlayer() {
        hideDeletePanel(getView());
        hideOpenInBrowserPanel();
        adapter.setIsPlayerOn(true);
        adapter.setSelectedPosition(playingVideoIndex);
        adapter.notifyDataSetChanged();
        try {
            if(getView()!=null){
                View container = getView().findViewById(R.id.container_player);
                if (container != null) {
                    container.setVisibility(View.VISIBLE);  
                }
            }
        } catch (Exception ex) {
            logger.error(ex);
            logger.warn("Error in showing player");
        }
    }

    private void hideOpenInBrowserPanel() {
        try {
            getView().findViewById(R.id.open_in_browser_panel).setVisibility(
                    View.GONE);
        } catch (Exception ex) {
            logger.error(ex);
            logger.warn("Error in hideOpenInBrowserPanel");
        }
    }

    private void showOpenInBrowserPanel() {
        try {
            if (!AppConstants.offline_flag) {
                if (isPlayerVisible()) {
                    hideOpenInBrowserPanel();
                } else {
                    final StringBuffer urlStringBuffer = new StringBuffer();
                    if (!openInBrowserUrl.contains("http://") && !openInBrowserUrl.contains("https://")) {
                        urlStringBuffer.append("http://");
                        urlStringBuffer.append(openInBrowserUrl);
                    } else {
                        urlStringBuffer.append(openInBrowserUrl);
                    }
                    getView().findViewById(R.id.open_in_browser_panel)
                    .setVisibility(View.VISIBLE);
                    TextView openInBrowserTv = (TextView) getView().findViewById(
                            R.id.open_in_browser_btn);
                    openInBrowserTv.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            BrowserUtil.open(getActivity(),
                                    urlStringBuffer.toString());
                        }
                    });
                }
            } else {
                hideOpenInBrowserPanel();
            }
        } catch (Exception ex) {
            logger.error(ex);
            logger.warn("Error in showOpenInBrowserPanel");
        }
    }

    public void onOffline() {
        if (!isLandscape) {
            AppConstants.offline_flag = true;
            if (offlineBar != null) {
                offlineBar.setVisibility(View.VISIBLE);
            }

            hideOpenInBrowserPanel();
            if (!myVideosFlag) {
                handleDeleteView();
                addDataToOfflineAdapter();
            }
        }
    }

    public void handleDeleteView() {
        if (isPlayerVisible()) {
            hideDeletePanel(getView());
        } else {
            if(downloadAvailable){
                showDeletePanel(getView());
            }
        }
    }

    public void onOnline() {
        AppConstants.offline_flag = false;
        if (!isLandscape) {
            if (offlineBar != null) {
                offlineBar.setVisibility(View.GONE);
            }
            if (!myVideosFlag) {
                AppConstants.videoListDeleteMode = false;
                addDataToOnlineAdapter();
                showOpenInBrowserPanel();
                hideDeletePanel(getView());
                hideConfirmDeleteDialog();
                handler.sendEmptyMessage(MSG_UPDATE_PROGRESS);
            }

        }
    }

    private void hideDeletePanel(View view) {
        try {
            View v = view.findViewById(R.id.delete_button_panel);
            if (v != null) {
                v.setVisibility(View.GONE);
            }

            handler.postDelayed(new Runnable() {
                public void run() {
                    try {
                        // hide checkbox in action bar
                        ((VideoListActivity) getActivity()).hideCheckBox();

                        // hide checkboxes in list
                        notifyAdapter();
                    } catch(Exception ex) {
                        logger.error(ex);
                    }
                }
            }, 300);

        } catch (Exception ex) {
            logger.warn("Error in hiding delete button Panel");
            logger.error(ex);
        }
    }

    private void showDeletePanel(View view) {
        try {
            hideOpenInBrowserPanel();

            if (isPlayerVisible()) {
                hideDeletePanel(view);
            } else {
                getView().findViewById(R.id.delete_button_panel).setVisibility(
                        View.VISIBLE);

                deleteButton = (Button) getView().findViewById(
                        R.id.delete_btn);
                final Button editButton = (Button) getView().findViewById(
                        R.id.edit_btn);
                final Button cancelButton = (Button) getView().findViewById(
                        R.id.cancel_btn);

                if (myVideosFlag) {
                    if (AppConstants.myVideosDeleteMode) {
                        deleteButton.setVisibility(View.VISIBLE);
                        cancelButton.setVisibility(View.VISIBLE);<commit_msg>Show edit button on Video Listing when switched to offline<commit_after>package org.edx.mobile.player;

import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import org.edx.mobile.R;
import org.edx.mobile.base.BaseFragmentActivity;
import org.edx.mobile.http.Api;
import org.edx.mobile.interfaces.SectionItemInterface;
import org.edx.mobile.logger.Logger;
import org.edx.mobile.model.api.EnrolledCoursesResponse;
import org.edx.mobile.model.api.LectureModel;
import org.edx.mobile.model.api.ProfileModel;
import org.edx.mobile.model.api.VideoResponseModel;
import org.edx.mobile.model.db.DownloadEntry;
import org.edx.mobile.module.analytics.ISegment;
import org.edx.mobile.module.analytics.SegmentFactory;
import org.edx.mobile.module.db.DataCallback;
import org.edx.mobile.module.db.IDatabase;
import org.edx.mobile.module.db.impl.DatabaseFactory;
import org.edx.mobile.module.prefs.PrefManager;
import org.edx.mobile.module.prefs.UserPrefs;
import org.edx.mobile.module.storage.IStorage;
import org.edx.mobile.module.storage.Storage;
import org.edx.mobile.task.CircularProgressTask;
import org.edx.mobile.util.AppConstants;
import org.edx.mobile.util.BrowserUtil;
import org.edx.mobile.util.MediaConsentUtils;
import org.edx.mobile.util.MemoryUtil;
import org.edx.mobile.util.NetworkUtil;
import org.edx.mobile.view.VideoListActivity;
import org.edx.mobile.view.adapters.MyAllVideoAdapter;
import org.edx.mobile.view.adapters.OfflineVideoAdapter;
import org.edx.mobile.view.adapters.OnlineVideoAdapter;
import org.edx.mobile.view.adapters.VideoBaseAdapter;
import org.edx.mobile.view.custom.ProgressWheel;
import org.edx.mobile.view.dialog.DeleteVideoDialogFragment;
import org.edx.mobile.view.dialog.IDialogCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class VideoListFragment extends Fragment {

    public static View offlineBar;
    private boolean isLandscape = false;
    private VideoBaseAdapter<SectionItemInterface> adapter;
    private ListView videoListView;
    private boolean myVideosFlag = false;
    private boolean isActivityStarted;
    protected IDatabase db;
    protected IStorage storage;
    private static final int MSG_UPDATE_PROGRESS = 1022;
    private DeleteVideoDialogFragment confirmDeleteFragment, downloadSizeExceedDialog;
    private String openInBrowserUrl;
    private String chapterName;
    private LectureModel lecture;
    private EnrolledCoursesResponse enrollment;
    private int playingVideoIndex = -1;
    private VideoListCallback callback;
    private DownloadEntry videoModel;
    private boolean downloadAvailable = false;
    private Button deleteButton;
    private ISegment segIO;
    private Api api;
    private final Logger logger = new Logger(getClass().getName());

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        initDB();
        segIO = SegmentFactory.getInstance();
        api = new Api(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return inflater.inflate(R.layout.fragment_video_list, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        restore(savedInstanceState);

        Intent extraIntent = getActivity().getIntent();
        if(extraIntent!=null){
            if (extraIntent.hasExtra("FromMyVideos")) {
                myVideosFlag = extraIntent.getBooleanExtra(
                        "FromMyVideos", false);
            }

            // read incoming chapter name
            if (chapterName == null) {
                chapterName = extraIntent.getStringExtra("chapter");
            }

            // read incoming lecture model
            if (lecture == null) {
                lecture = (LectureModel) extraIntent
                        .getSerializableExtra("lecture");
            }
            // read incoming enrollment model
            if (enrollment == null) {
                enrollment = (EnrolledCoursesResponse) extraIntent
                        .getSerializableExtra(BaseFragmentActivity.EXTRA_ENROLLMENT);
            }
        }

        if (chapterName == null) {
            if (enrollment != null && lecture != null) {
                if (lecture.chapter != null) {
                    chapterName = lecture.chapter.chapter;
                }
            }
        }

        videoListView = (ListView) getView().findViewById(R.id.list_video);

        if (videoListView != null) {
            isLandscape = false;

            videoListView.setEmptyView(getView().findViewById(
                    R.id.empty_list_view));
            offlineBar = (View) getView().findViewById(R.id.offline_bar);

            if (!(NetworkUtil.isConnected(getActivity()))) {
                if (offlineBar != null)
                    offlineBar.setVisibility(View.VISIBLE);
                showDeletePanel(getView());
                AppConstants.offline_flag = true;
            } else {
                if (offlineBar != null) {
                    offlineBar.setVisibility(View.GONE);
                }
                AppConstants.offline_flag = false;
            }

            setAdaptertoVideoList();

        } else {
            isLandscape = true;
            // probably the landscape player view, so hide action bar
            ActionBar bar = getActivity().getActionBar();
            if(bar!=null){
                bar.hide();
            }
        }
    }

    public void setAdaptertoVideoList(){
        if (!myVideosFlag) {
            if (AppConstants.offline_flag) {
                addDataToOfflineAdapter();
            } else {
                addDataToOnlineAdapter();
            }
        } else {
            showDeletePanel(getView());
            hideOpenInBrowserPanel();
            addDataToMyVideoAdapter();
        }
    }
    
    
    private void addDataToOnlineAdapter() {
        try {
            String selectedId = null;
            if(adapter!=null){
                selectedId = adapter.getVideoId();
            }
            adapter = new OnlineVideoAdapter(getActivity(), db , storage) {
                @Override
                public void onItemClicked(final SectionItemInterface model, final int position) {
                    if (model.isDownload()) {
                        // hide delete panel first, so that multiple-tap is blocked
                        hideDeletePanel(VideoListFragment.this.getView());

                        if (!NetworkUtil.isConnected(getContext())) {
                            ((VideoListActivity) getActivity()).showInfoMessage(getString(R.string.need_data));
                            notifyAdapter();
                        } else {
                            IDialogCallback dialogCallback = new IDialogCallback() {
                                @Override
                                public void onPositiveClicked() {
                                    startOnlinePlay(model, position);
                                }

                                @Override
                                public void onNegativeClicked() {
                                    //
                                }
                            };
                            MediaConsentUtils.consentToMediaDownload(getActivity(), dialogCallback);
                        }
                    }
                }

                @Override
                public void download(final DownloadEntry videoData, final ProgressWheel progressWheel) {
                    try {
                        if (!NetworkUtil.isConnected(getContext())) {
                            ((VideoListActivity) getActivity()).showInfoMessage(getString(R.string.need_data));
                            notifyAdapter();
                        } else {
                            if (!(getActivity() instanceof VideoListActivity)) {
                                return;
                            }
                            IDialogCallback dialogCallback = new IDialogCallback() {
                                @Override
                                public void onPositiveClicked() {
                                    startOnlineDownload(videoData, progressWheel);
                                }

                                @Override
                                public void onNegativeClicked() {
                                    //
                                }
                            };
                            MediaConsentUtils.consentToMediaDownload(getActivity(), dialogCallback);
                        }

                    } catch (Exception e) {
                        logger.error(e);
                    }
                }
            };

            if(selectedId!=null){
                adapter.setVideoId(selectedId);
            }
            videoListView.setAdapter(adapter);
            videoListView.setOnItemClickListener(adapter);

            if (lecture != null) {
                setActivityTitle(lecture.name);
                for (VideoResponseModel m : lecture.videos) {
                    if (openInBrowserUrl == null
                            || openInBrowserUrl.equalsIgnoreCase("")) {
                        openInBrowserUrl = m.section_url;
                    }
                    final DownloadEntry downloadEntry = (DownloadEntry) storage
                            .getDownloadEntryfromVideoResponseModel(m);
                    adapter.add(downloadEntry);
                }

            } else {
                setActivityTitle(chapterName);

                ArrayList<SectionItemInterface> list = api
                        .getLiveOrganizedVideosByChapter(enrollment.getCourse()
                                .getId(), chapterName);
                for (SectionItemInterface m : list) {
                    if (m.isVideo()) {
                        VideoResponseModel vidmodel = (VideoResponseModel) m;
                        DownloadEntry downloadEntry = (DownloadEntry) storage
                                .getDownloadEntryfromVideoResponseModel(vidmodel);
                        adapter.add(downloadEntry);
                    } else {
                        adapter.add(m);
                    }
                }
            }
            adapter.setSelectedPosition(playingVideoIndex);
            adapter.notifyDataSetChanged();
        } catch (Exception e) {
            logger.error(e);
        }
    }

    private void startOnlinePlay(SectionItemInterface model, int position){
        // hide delete panel first, so that multiple-tap is blocked
        hideDeletePanel(VideoListFragment.this.getView());

        if ( !isPlayerVisible()) {
            // don't try to showPlayer() if already shown here
            // this will cause player to freeze
            showPlayer();
        }

        DownloadEntry de = (DownloadEntry) model;
        addVideoDatatoDb(de);
        adapter.setVideoId(de.videoId);

        // initialize index for this model
        playingVideoIndex = position;

        play(model);
        notifyAdapter();
    }


    private void startOnlineDownload(DownloadEntry videoData, ProgressWheel progressWheel){
        long downloadSize = videoData.size;
        if (downloadSize > MemoryUtil
                .getAvailableExternalMemory(getActivity())) {
            ((VideoListActivity) getActivity())
                    .showInfoMessage(getString(R.string.file_size_exceeded));
            notifyAdapter();
        } else {
            if (downloadSize < MemoryUtil.GB) {
                startDownload(videoData, progressWheel);
            } else {
                showStartDownloadDialog(videoData, progressWheel);
            }
        }
    }

    private void addDataToOfflineAdapter() {
        try {
            String selectedId = null;
            if(adapter!=null){
                selectedId = adapter.getVideoId();
            }
            adapter = new OfflineVideoAdapter(getActivity(), db) {
                @Override
                public void onItemClicked(SectionItemInterface model,
                        int position) {
                    if (model.isDownload()) {

                        DownloadEntry downloadEntry = (DownloadEntry) model;
                        if (downloadEntry.isDownloaded()) {
                            adapter.setVideoId(downloadEntry.videoId);
                            // hide delete panel first, so that multiple-tap is blocked
                            hideDeletePanel(VideoListFragment.this.getView());

                            showPlayer();
                            // initialize index for this model
                            playingVideoIndex = position;

                            play(model);
                            notifyAdapter();
                        } else {
                            ((VideoListActivity) getActivity())
                                    .showOfflineAccessMessage();
                        }
                    }
                }

                @Override
                public void onSelectItem() {
                    handleCheckboxSelection();
                }
            };
            if(selectedId!=null){
                adapter.setVideoId(selectedId);
            }
            videoListView.setAdapter(adapter);
            videoListView.setOnItemClickListener(adapter);

            setActivityTitle(chapterName);

            ArrayList<SectionItemInterface> list = api
                    .getLiveOrganizedVideosByChapter(enrollment.getCourse()
                            .getId(), chapterName);
            downloadAvailable = false;
            for (SectionItemInterface m : list) {
                if (m.isVideo()) {
                    VideoResponseModel vidmodel = (VideoResponseModel) m;
                    DownloadEntry downloadEntry = (DownloadEntry) storage
                            .getDownloadEntryfromVideoResponseModel(vidmodel);
                    adapter.add(downloadEntry);
                    if(downloadEntry.isDownloaded()){
                        downloadAvailable = true;
                    }
                } else {
                    adapter.add(m);
                }
            }

            if(!downloadAvailable){
                hideDeletePanel(getView());
            }

            adapter.setSelectedPosition(playingVideoIndex);
            adapter.notifyDataSetChanged();
        } catch (Exception e) {
            logger.error(e);
        }

    }

    private void addDataToMyVideoAdapter() {
        try {
            String selectedId = null;
            if(adapter!=null){
                selectedId = adapter.getVideoId();
            }

            adapter = new MyAllVideoAdapter(getActivity(), db) {
                @Override
                public void onItemClicked(SectionItemInterface model,
                        int position) {
                    if (!AppConstants.myVideosDeleteMode) {
                        if (model.isDownload()) {
                            DownloadEntry downloadEntry = (DownloadEntry) model;
                            if (downloadEntry.isDownloaded()) {
                                adapter.setVideoId(downloadEntry.videoId);
                                // hide delete panel first, so that multiple-tap is blocked
                                hideDeletePanel(VideoListFragment.this.getView());
                                showPlayer();

                                // initialize index for this model
                                playingVideoIndex = position;
                                play(model);
                                notifyAdapter();
                            }
                        }
                    }
                }

                @Override
                public void onSelectItem() {
                    handleCheckboxSelection();
                }
            };
            if(selectedId!=null){
                adapter.setVideoId(selectedId);
            }

            videoListView.setAdapter(adapter);
            videoListView.setOnItemClickListener(adapter);

            setActivityTitle(enrollment.getCourse().getName());
            try{
                segIO.screenViewsTracking("My Videos - All Videos - "
                        + enrollment.getCourse().getName());
            }catch(Exception e){
                logger.error(e);
            }

            ArrayList<SectionItemInterface> list = storage
                    .getSortedOrganizedVideosByCourse(enrollment.getCourse().getId());
            downloadAvailable = false;
            if(list==null||list.size()==0){
                hideDeletePanel(getView());
                downloadAvailable = false;
            }else{
                downloadAvailable = true;
            }

            for (SectionItemInterface m : list) {
                adapter.add(m);
            }
            notifyAdapter();
        } catch (Exception e) {
            logger.error(e);
        }
    }

    /**
     * This function sets text to the title in Action Bar
     * @param title
     */
    private void setActivityTitle(String title){
        try{
            getActivity().setTitle(title);
        }catch(Exception e){
            logger.error(e);
        }
    }

    private void play(SectionItemInterface model) {
        if (model instanceof DownloadEntry) {
            hideOpenInBrowserPanel();

            DownloadEntry v = (DownloadEntry) model;
            try {
                String prefName = PrefManager.getPrefNameForLastAccessedBy(getProfile()
                        .username, v.eid);
                PrefManager prefManager = new PrefManager(getActivity(), prefName);
                VideoResponseModel vrm = api.getVideoById(v.eid, v.videoId);
                prefManager.putLastAccessedSubsection(vrm.getSection().id, false);

                // capture chapter name
                if (chapterName == null) {
                    // capture the chapter name of this video
                    chapterName = v.chapter;
                }

                if (callback != null) {
                    videoModel = v;
                    callback.playVideoModel(v);
                    adapter.setVideoId(videoModel.videoId);
                    adapter.setSelectedPosition(playingVideoIndex);
                    adapter.notifyDataSetChanged();
                }
            } catch (Exception e) {
                logger.error(e);
            }

        }
    }

    private void showPlayer() {
        hideDeletePanel(getView());
        hideOpenInBrowserPanel();
        adapter.setIsPlayerOn(true);
        adapter.setSelectedPosition(playingVideoIndex);
        adapter.notifyDataSetChanged();
        try {
            if(getView()!=null){
                View container = getView().findViewById(R.id.container_player);
                if (container != null) {
                    container.setVisibility(View.VISIBLE);  
                }
            }
        } catch (Exception ex) {
            logger.error(ex);
            logger.warn("Error in showing player");
        }
    }

    private void hideOpenInBrowserPanel() {
        try {
            getView().findViewById(R.id.open_in_browser_panel).setVisibility(
                    View.GONE);
        } catch (Exception ex) {
            logger.error(ex);
            logger.warn("Error in hideOpenInBrowserPanel");
        }
    }

    private void showOpenInBrowserPanel() {
        try {
            if (!AppConstants.offline_flag) {
                if (isPlayerVisible()) {
                    hideOpenInBrowserPanel();
                } else {
                    final StringBuffer urlStringBuffer = new StringBuffer();
                    if (!openInBrowserUrl.contains("http://") && !openInBrowserUrl.contains("https://")) {
                        urlStringBuffer.append("http://");
                        urlStringBuffer.append(openInBrowserUrl);
                    } else {
                        urlStringBuffer.append(openInBrowserUrl);
                    }
                    getView().findViewById(R.id.open_in_browser_panel)
                    .setVisibility(View.VISIBLE);
                    TextView openInBrowserTv = (TextView) getView().findViewById(
                            R.id.open_in_browser_btn);
                    openInBrowserTv.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            BrowserUtil.open(getActivity(),
                                    urlStringBuffer.toString());
                        }
                    });
                }
            } else {
                hideOpenInBrowserPanel();
            }
        } catch (Exception ex) {
            logger.error(ex);
            logger.warn("Error in showOpenInBrowserPanel");
        }
    }

    public void onOffline() {
        if (!isLandscape) {
            AppConstants.offline_flag = true;
            if (offlineBar != null) {
                offlineBar.setVisibility(View.VISIBLE);
            }

            hideOpenInBrowserPanel();
            if (!myVideosFlag) {
                addDataToOfflineAdapter();
                //Call handleDeleteView only after adding data to adapter
                handleDeleteView();
            }
        }
    }

    public void handleDeleteView() {
        if (isPlayerVisible()) {
            hideDeletePanel(getView());
        } else {
            if(downloadAvailable){
                showDeletePanel(getView());
            }
        }
    }

    public void onOnline() {
        AppConstants.offline_flag = false;
        if (!isLandscape) {
            if (offlineBar != null) {
                offlineBar.setVisibility(View.GONE);
            }
            if (!myVideosFlag) {
                AppConstants.videoListDeleteMode = false;
                addDataToOnlineAdapter();
                showOpenInBrowserPanel();
                hideDeletePanel(getView());
                hideConfirmDeleteDialog();
                handler.sendEmptyMessage(MSG_UPDATE_PROGRESS);
            }

        }
    }

    private void hideDeletePanel(View view) {
        try {
            View v = view.findViewById(R.id.delete_button_panel);
            if (v != null) {
                v.setVisibility(View.GONE);
            }

            handler.postDelayed(new Runnable() {
                public void run() {
                    try {
                        // hide checkbox in action bar
                        ((VideoListActivity) getActivity()).hideCheckBox();

                        // hide checkboxes in list
                        notifyAdapter();
                    } catch(Exception ex) {
                        logger.error(ex);
                    }
                }
            }, 300);

        } catch (Exception ex) {
            logger.warn("Error in hiding delete button Panel");
            logger.error(ex);
        }
    }

    private void showDeletePanel(View view) {
        try {
            hideOpenInBrowserPanel();

            if (isPlayerVisible()) {
                hideDeletePanel(view);
            } else {
                view.findViewById(R.id.delete_button_panel).setVisibility(
                        View.VISIBLE);

                deleteButton = (Button) view.findViewById(
                        R.id.delete_btn);
                final Button editButton = (Button) view.findViewById(
                        R.id.edit_btn);
                final Button cancelButton = (Button) view.findViewById(
                        R.id.cancel_btn);

                if (myVideosFlag) {
                    if (AppConstants.myVideosDeleteMode) {
                        deleteButton.setVisibility(View.VISIBLE);
                        cancelButton.setVisibility(View.VISIBLE);
{'fraction_non_alphanumeric': 0.08455874854683772, 'fraction_numerical': 0.0004486957231139483, 'mean_word_length': 1.4357675111773471, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 137, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6079856', 'n_tokens_mistral': 11807, 'n_tokens_neox': 11008, 'n_words': 2108}