package com.app.simplitend.appblocking;

import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.widget.SwitchCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.app.simplitend.R;
import com.app.simplitend.apputils.AppUtil;

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

public class MyAppsAdapter extends RecyclerView.Adapter<MyAppsAdapter.ViewHolder> {
    private List<AppList> listdata;
    private Context context;
    private MySharedPref mySharedPref;
    boolean isWhiteList;
    ItemClicked itemClicked;

    // RecyclerView recyclerView;
    public MyAppsAdapter(Context context, List<AppList> listdata, boolean isWhiteList, ItemClicked itemClicked) {
        this.context = context;
        this.listdata = listdata;
        this.isWhiteList = isWhiteList;
        this.itemClicked = itemClicked;
        mySharedPref = new MySharedPref(context);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View listItem = layoutInflater.inflate(R.layout.app_list_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(listItem);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.tvAppName.setText(listdata.get(position).getName());
        holder.ivAppIcon.setImageDrawable(listdata.get(position).getIcon());

        if (!isSelectedApp(listdata.get(position).getPackages())) {
            holder.ivAddRemove.setImageResource(R.drawable.minus);
        } else {
            holder.ivAddRemove.setImageResource(R.drawable.plus);
        }

        if (isWhiteList) {
            holder.ivAddRemove.setVisibility(View.GONE);
        }

        holder.ivAppIcon.setOnClickListener(v -> {
            if (itemClicked != null && isWhiteList){
                itemClicked.onCLick(listdata.get(position));
            }
        });

        holder.ivAddRemove.setOnClickListener(v -> {

            if (!isAccessibilityAppBlockingEnabled()) {
                openAccessibilityDialog();
            } else {
                addAppsInList(listdata.get(position).getPackages());

                if (!isSelectedApp(listdata.get(position).getPackages())) {
                    holder.ivAddRemove.setImageResource(R.drawable.minus);
                } else {
                    holder.ivAddRemove.setImageResource(R.drawable.plus);
                }

                itemClicked.onCLick(listdata.get(position));
            }

        });

    }

    public boolean isSelectedApp(String packageName) {
        if (mySharedPref.checkKey("APP_LIST")) {
            ArrayList<String> myList = new ArrayList<>(mySharedPref.getArrayList("APP_LIST"));
            return myList.contains(packageName);
        }
        return false;
    }

    public void addAppsInList(String packageName) {
        ArrayList<String> myList = new ArrayList<>();

        if (mySharedPref.checkKey("APP_LIST")) {

            myList.addAll(mySharedPref.getArrayList("APP_LIST"));

            if (myList.contains(packageName)) {
                myList.remove(packageName);
                mySharedPref.setArrayList("APP_LIST", myList);
            } else {
                myList.add(packageName);
                mySharedPref.setArrayList("APP_LIST", myList);
            }
        } else {
            myList.add(packageName);
            mySharedPref.setArrayList("APP_LIST", myList);
        }
    }

    @Override
    public int getItemCount() {
        return listdata.size();
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    interface ItemClicked {
        void onCLick(AppList appList);
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        public TextView tvAppName;
        public ImageView ivAppIcon, ivAddRemove;
        public SwitchCompat swOnOff;

        public ViewHolder(View itemView) {
            super(itemView);
            this.tvAppName = (TextView) itemView.findViewById(R.id.tvAppName);
            this.ivAppIcon = (ImageView) itemView.findViewById(R.id.iv_app_icon);
            this.ivAddRemove = (ImageView) itemView.findViewById(R.id.iv_add_remove);
//            this.swOnOff = (SwitchCompat) itemView.findViewById(R.id.swOnOff);
        }
    }

    private boolean isAccessibilityAppBlockingEnabled() {
        int accessibilityEnabled = 0;
        final String service = context.getPackageName() + "/" + TopAppDetectionService.class.getCanonicalName();

        try {
            accessibilityEnabled = Settings.Secure.getInt(
                    context.getContentResolver(),
                    Settings.Secure.ACCESSIBILITY_ENABLED);

        } catch (Settings.SettingNotFoundException e) {
            Log.e("TAG", "Error finding setting, default accessibility to not found: "
                    + e.getMessage());
        }

        TextUtils.SimpleStringSplitter colonSplitter = new TextUtils.SimpleStringSplitter(':');

        if (accessibilityEnabled == 1) {
            String settingValue = Settings.Secure.getString(
                    context.getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                colonSplitter.setString(settingValue);
                while (colonSplitter.hasNext()) {
                    String accessibilityService = colonSplitter.next();
                    if (accessibilityService.equalsIgnoreCase(service)) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    private void openAccessibilityDialog() {

        AppUtil.showAlert(context,
                "Accessibility Permission",
                "Frequently used apps enables you to select your top apps, ensuring quick access and avoid distraction..\nChosen apps will be granted access, while all remaining apps will be restricted.\n\nTo activate, click on Go to settings -> Installed/Downloaded apps -> SimpliTend -> Turn on the permission.",
                "Go to settings", (dialog, id) -> {
                    Intent accessibilityIntent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                    context.startActivity(accessibilityIntent);
                },
                "Cancel",(dialog, id) -> {
                    //  Action for 'NO' Button
                    dialog.cancel();
                });
    }
}  