<commit_before>package org.stepic.droid.ui.adapters;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.stepic.droid.R;
import org.stepic.droid.analytic.Analytic;
import org.stepic.droid.base.MainApplication;
import org.stepic.droid.core.IScreenManager;
import org.stepic.droid.core.IShell;
import org.stepic.droid.core.presenters.CalendarPresenter;
import org.stepic.droid.model.Course;
import org.stepic.droid.model.Section;
import org.stepic.droid.store.CleanManager;
import org.stepic.droid.store.IDownloadManager;
import org.stepic.droid.store.operations.DatabaseFacade;
import org.stepic.droid.ui.dialogs.ExplainExternalStoragePermissionDialog;
import org.stepic.droid.ui.listeners.OnClickLoadListener;
import org.stepic.droid.ui.listeners.StepicOnClickItemListener;
import org.stepic.droid.util.AppConstants;
import org.stepic.droid.util.ColorUtil;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;

public class SectionAdapter extends RecyclerView.Adapter<SectionAdapter.GenericViewHolder> implements OnClickLoadListener {
    private final static String SECTION_TITLE_DELIMETER = ". ";

    public static final int TYPE_SECTION_ITEM = 1;
    public static final int TYPE_TITLE = 2;

    public static final int SECTION_LIST_DELTA = 1;

    private int defaultHighlightPosition = -1;

    @Inject
    IScreenManager screenManager;
    @Inject
    IDownloadManager downloadManager;

    @Inject
    DatabaseFacade databaseFacade;

    @Inject
    IShell shell;

    @Inject
    CleanManager cleaner;

    @Inject
    Analytic analytic;

    private List<Section> sections;
    private Context mContext;
    private AppCompatActivity activity;
    private CalendarPresenter calendarPresenter;
    private Course course;
    private boolean needShowCalendarWidget;
    private Drawable highlightDrawable;
    @ColorInt
    private int defaultColor;
    private final int durationMillis = 3000;

    public void setDefaultHighlightPosition(int defaultHighlightPosition) {
        this.defaultHighlightPosition = defaultHighlightPosition;
    }

    public SectionAdapter(List<Section> sections, Context mContext, AppCompatActivity activity, CalendarPresenter calendarPresenter) {
        this.sections = sections;
        this.mContext = mContext;
        this.activity = activity;
        this.calendarPresenter = calendarPresenter;
        highlightDrawable = ContextCompat.getDrawable(mContext, R.drawable.section_background);
        defaultColor = ColorUtil.INSTANCE.getColorArgb(R.color.stepic_white, mContext);
        MainApplication.component().inject(this);
    }


    @Override
    public GenericViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_SECTION_ITEM) {
            View v = LayoutInflater.from(mContext).inflate(R.layout.section_item, parent, false);
            return new SectionViewHolder(v);
        } else if (viewType == TYPE_TITLE) {
            View v = LayoutInflater.from(mContext).inflate(R.layout.export_calendar_view, parent, false);
            return new CalendarViewHolder(v);
        } else {
            return null;
        }
    }


    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return TYPE_TITLE;
        } else {
            return TYPE_SECTION_ITEM;
        }
    }


    @Override
    public void onBindViewHolder(GenericViewHolder holder, int position) {
        holder.setDataOnView(position);
    }

    @Override
    public int getItemCount() {
        return sections.size() + SECTION_LIST_DELTA;
    }


    public void requestClickLoad(int position) {
        onClickLoad(position);
    }

    public void setCourse(Course course) {
        this.course = course;
    }

    @Override
    public void onClickLoad(int adapterPosition) {
        int sectionPosition = adapterPosition - SECTION_LIST_DELTA;
        if (sectionPosition >= 0 && sectionPosition < sections.size()) {
            Section section = sections.get(sectionPosition);

            int permissionCheck = ContextCompat.checkSelfPermission(MainApplication.getAppContext(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);

            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                shell.getSharedPreferenceHelper().storeTempPosition(adapterPosition);
                if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

                    // Show an explanation to the user *asynchronously* -- don't block
                    // this thread waiting for the user's response! After the user
                    // sees the explanation, try again to request the permission.

                    DialogFragment dialog = ExplainExternalStoragePermissionDialog.newInstance();
                    if (!dialog.isAdded()) {
                        dialog.show(activity.getSupportFragmentManager(), null);
                    }

                } else {
                    // No explanation needed, we can request the permission.

                    ActivityCompat.requestPermissions(activity,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            AppConstants.REQUEST_EXTERNAL_STORAGE);

                }
                return;
            }

            if (section.is_cached()) {
                analytic.reportEvent(Analytic.Interaction.CLICK_DELETE_SECTION, section.getId() + "");
                cleaner.removeSection(section);
                section.set_loading(false);
                section.set_cached(false);
                databaseFacade.updateOnlyCachedLoadingSection(section);
                notifyItemChanged(adapterPosition);
            } else {
                if (section.is_loading()) {
                    analytic.reportEvent(Analytic.Interaction.CLICK_CANCEL_SECTION, section.getId() + "");
                    screenManager.showDownload(mContext);
                } else {

//                    DialogFragment dialogFragment = VideoQualityDetailedDialog.Companion.newInstance();
//                    if (!dialogFragment.isAdded()) {
//                        dialogFragment.show(mActivity.getSupportFragmentManager(), null);
//                    }
                    analytic.reportEvent(Analytic.Interaction.CLICK_CACHE_SECTION, section.getId() + "");
                    section.set_cached(false);
                    section.set_loading(true);
                    databaseFacade.updateOnlyCachedLoadingSection(section);
                    downloadManager.addSection(section);
                    notifyItemChanged(adapterPosition);
                }
            }
        }
    }

    public void setNeedShowCalendarWidget(boolean needShowCalendarWidget) {
        this.needShowCalendarWidget = needShowCalendarWidget;
    }

    class SectionViewHolder extends GenericViewHolder implements StepicOnClickItemListener {

        @BindView(R.id.cv)
        ViewGroup cv;
<commit_msg>update section state on worker thread<commit_after>package org.stepic.droid.ui.adapters;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.stepic.droid.R;
import org.stepic.droid.analytic.Analytic;
import org.stepic.droid.base.MainApplication;
import org.stepic.droid.core.IScreenManager;
import org.stepic.droid.core.IShell;
import org.stepic.droid.core.presenters.CalendarPresenter;
import org.stepic.droid.model.Course;
import org.stepic.droid.model.Section;
import org.stepic.droid.store.CleanManager;
import org.stepic.droid.store.IDownloadManager;
import org.stepic.droid.store.operations.DatabaseFacade;
import org.stepic.droid.ui.dialogs.ExplainExternalStoragePermissionDialog;
import org.stepic.droid.ui.listeners.OnClickLoadListener;
import org.stepic.droid.ui.listeners.StepicOnClickItemListener;
import org.stepic.droid.util.AppConstants;
import org.stepic.droid.util.ColorUtil;

import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

import javax.inject.Inject;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;

public class SectionAdapter extends RecyclerView.Adapter<SectionAdapter.GenericViewHolder> implements OnClickLoadListener {
    private final static String SECTION_TITLE_DELIMETER = ". ";

    public static final int TYPE_SECTION_ITEM = 1;
    public static final int TYPE_TITLE = 2;

    public static final int SECTION_LIST_DELTA = 1;

    private int defaultHighlightPosition = -1;

    @Inject
    IScreenManager screenManager;

    @Inject
    IDownloadManager downloadManager;

    @Inject
    DatabaseFacade databaseFacade;

    @Inject
    IShell shell;

    @Inject
    CleanManager cleaner;

    @Inject
    Analytic analytic;

    @Inject
    ThreadPoolExecutor threadPoolExecutor;

    private List<Section> sections;
    private Context mContext;
    private AppCompatActivity activity;
    private CalendarPresenter calendarPresenter;
    private Course course;
    private boolean needShowCalendarWidget;
    private Drawable highlightDrawable;
    @ColorInt
    private int defaultColor;
    private final int durationMillis = 3000;

    public void setDefaultHighlightPosition(int defaultHighlightPosition) {
        this.defaultHighlightPosition = defaultHighlightPosition;
    }

    public SectionAdapter(List<Section> sections, Context mContext, AppCompatActivity activity, CalendarPresenter calendarPresenter) {
        this.sections = sections;
        this.mContext = mContext;
        this.activity = activity;
        this.calendarPresenter = calendarPresenter;
        highlightDrawable = ContextCompat.getDrawable(mContext, R.drawable.section_background);
        defaultColor = ColorUtil.INSTANCE.getColorArgb(R.color.stepic_white, mContext);
        MainApplication.component().inject(this);
    }


    @Override
    public GenericViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_SECTION_ITEM) {
            View v = LayoutInflater.from(mContext).inflate(R.layout.section_item, parent, false);
            return new SectionViewHolder(v);
        } else if (viewType == TYPE_TITLE) {
            View v = LayoutInflater.from(mContext).inflate(R.layout.export_calendar_view, parent, false);
            return new CalendarViewHolder(v);
        } else {
            return null;
        }
    }


    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return TYPE_TITLE;
        } else {
            return TYPE_SECTION_ITEM;
        }
    }


    @Override
    public void onBindViewHolder(GenericViewHolder holder, int position) {
        holder.setDataOnView(position);
    }

    @Override
    public int getItemCount() {
        return sections.size() + SECTION_LIST_DELTA;
    }


    public void requestClickLoad(int position) {
        onClickLoad(position);
    }

    public void setCourse(Course course) {
        this.course = course;
    }

    @Override
    public void onClickLoad(int adapterPosition) {
        int sectionPosition = adapterPosition - SECTION_LIST_DELTA;
        if (sectionPosition >= 0 && sectionPosition < sections.size()) {
            final Section section = sections.get(sectionPosition);

            int permissionCheck = ContextCompat.checkSelfPermission(MainApplication.getAppContext(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);

            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                shell.getSharedPreferenceHelper().storeTempPosition(adapterPosition);
                if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

                    // Show an explanation to the user *asynchronously* -- don't block
                    // this thread waiting for the user's response! After the user
                    // sees the explanation, try again to request the permission.

                    DialogFragment dialog = ExplainExternalStoragePermissionDialog.newInstance();
                    if (!dialog.isAdded()) {
                        dialog.show(activity.getSupportFragmentManager(), null);
                    }

                } else {
                    // No explanation needed, we can request the permission.

                    ActivityCompat.requestPermissions(activity,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            AppConstants.REQUEST_EXTERNAL_STORAGE);

                }
                return;
            }

            if (section.is_cached()) {
                analytic.reportEvent(Analytic.Interaction.CLICK_DELETE_SECTION, section.getId() + "");
                cleaner.removeSection(section);
                section.set_loading(false);
                section.set_cached(false);
                threadPoolExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        databaseFacade.updateOnlyCachedLoadingSection(section);
                    }
                });
                notifyItemChanged(adapterPosition);
            } else {
                if (section.is_loading()) {
                    analytic.reportEvent(Analytic.Interaction.CLICK_CANCEL_SECTION, section.getId() + "");
                    screenManager.showDownload(mContext);
                } else {

//                    DialogFragment dialogFragment = VideoQualityDetailedDialog.Companion.newInstance();
//                    if (!dialogFragment.isAdded()) {
//                        dialogFragment.show(mActivity.getSupportFragmentManager(), null);
//                    }
                    analytic.reportEvent(Analytic.Interaction.CLICK_CACHE_SECTION, section.getId() + "");
                    section.set_cached(false);
                    section.set_loading(true);
                    threadPoolExecutor.execute(new Runnable() {
                        @Override
                        public void run() {
                            databaseFacade.updateOnlyCachedLoadingSection(section);
                        }
                    });
                    downloadManager.addSection(section);
                    notifyItemChanged(adapterPosition);
                }
            }
        }
    }

    public void setNeedShowCalendarWidget(boolean needShowCalendarWidget) {
        this.needShowCalendarWidget = needShowCalendarWidget;
    }

    class SectionViewHolder extends GenericViewHolder implements StepicOnClickItemListener {

        @BindView(R.id.cv)
        ViewGroup cv;

{'fraction_non_alphanumeric': 0.07985435369451943, 'fraction_numerical': 0.001883357398455647, 'mean_word_length': 2.606520262621689, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2404380', 'n_tokens_mistral': 4220, 'n_tokens_neox': 4011, 'n_words': 787}