package com.android.launcher3.settings;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.launcher3.R;
import com.android.launcher3.graphics.DrawableFactory;
import com.secspace.lib.common.utils.Prefs;

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


public class AppChooseListAdapter extends BaseRecyclerViewAdapter<AppModel> {
    public static final int SYSTEM_APP_FLAG = 0;
    public static final int USER_APP_FLAG = 1;
    public static final String TAG = "AppChooseListAdapter";
    private List<String> flagShow = new ArrayList<>();
    private int mAppTypeFlag;

    public AppChooseListAdapter(int flag) {
        mAppTypeFlag = flag;
    }

    @SuppressLint("ResourceAsColor")
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        super.onBindViewHolder(holder, position);
        MyViewHolder mHolder = (MyViewHolder) holder;
        ImageView imgIcon = mHolder.get(R.id.icon);
        final CheckedTextView tvName = mHolder.get(R.id.name);
        final RelativeLayout parent = mHolder.get(R.id.parent);

        imgIcon.setImageDrawable(mList.get(position).getIcon());
        tvName.setText(mList.get(position).getLabel());
        final String packageName = mList.get(position).getApplicationPackageName();

        if (flagShow != null && flagShow.contains(packageName)) {
            tvName.setChecked(true);
            parent.setBackgroundResource(R.drawable.rev_select);
        } else {
            tvName.setChecked(false);
            parent.setBackgroundResource(R.drawable.rev_normal);
        }

        parent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvName.toggle();
                if (tvName.isChecked()) {
                    flagShow.add(packageName);
                    parent.setBackgroundResource(R.drawable.rev_select);
                } else {
                    flagShow.remove(packageName);
                    parent.setBackgroundResource(R.drawable.rev_normal);
                }
            }
        });
    }

    public void saveResult(Context context) {
        if (mAppTypeFlag == SYSTEM_APP_FLAG) {
            Prefs.setSystemShowAppPkgs(context, flagShow);
        } else {
            Prefs.setUserShowAppPkgs(context, flagShow);
        }
    }

    public void readResult(Context context) {
        if (mAppTypeFlag == SYSTEM_APP_FLAG) {
            flagShow = Prefs.getSystemShowAppPkgs(context);
        } else {
            flagShow = Prefs.getUserShowAppPkgs(context);
        }
    }
}
