package com.app.simplitend.appblocking;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.provider.Telephony;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.simplitend.R;
import com.app.simplitend.apputils.AppUtil;
import com.app.simplitend.apputils.PatientDataCache;
import com.app.simplitend.apputils.RetrofitHelper;
import com.app.simplitend.databinding.FuaEduDialogBinding;
import com.bumptech.glide.Glide;

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

public class FUAActivity extends AppCompatActivity {

    SwitchCompat swBlock;
    RecyclerView rvApps, rvWhiteApps;
    MyAppsAdapter adapter, whiteListAdapter;
    MySharedPref mySharedPref;
    List<AppList> whiteList;

    TextView all_apps_title;

    LinearLayout no_fua;
    TextView no_fua_txt, fua_sub_title;

    List<AppList> installed_app_list;

    public static final String IS_FROM_DASHBOARD = "is_from_dashboard";
    protected boolean isFromDashboard;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fua);

        isFromDashboard = getIntent().getBooleanExtra(IS_FROM_DASHBOARD, false);

//        swBlock = (SwitchCompat) findViewById(R.id.swBlock);
        rvApps = (RecyclerView) findViewById(R.id.rvApps);
        rvWhiteApps = (RecyclerView) findViewById(R.id.rv_white_apps);
        mySharedPref = new MySharedPref(FUAActivity.this);
        no_fua = findViewById(R.id.no_fua);
        no_fua_txt = findViewById(R.id.no_fua_text);
        all_apps_title = findViewById(R.id.all_app_tile);
        fua_sub_title = findViewById(R.id.fua_sub_title);

        if (AppUtil.shouldShowFUADialog(this) && isFromDashboard){
            FuaEduDialogBinding dialogBinding = FuaEduDialogBinding.inflate(getLayoutInflater());
            Dialog fuaDialog = new Dialog(this, R.style.BottomSheetDialog);
            fuaDialog.setContentView(dialogBinding.getRoot());

            PatientDataCache.getPatientData(this, (patientData -> {
                if (patientData != null && patientData.profile_photo != null){
                    Glide.with(this)
                            .load(RetrofitHelper.IMAGE_BASE_URL + patientData.profile_photo)
                            .placeholder(R.drawable.senior_img)
                            .error(R.drawable.senior_img)
                            .fitCenter()
                            .into(dialogBinding.seniorImg);
                }
            }), false);

            dialogBinding.checkBox.setOnCheckedChangeListener((compoundButton, b) -> {
                AppUtil.setShouldShowFuaDialog(this, !b);
            });

            dialogBinding.close.setOnClickListener(v -> fuaDialog.dismiss());
            fuaDialog.show();
        }
        
        if (!isAccessibilityAppBlockingEnabled()) {
            openAccessibilityDialog();
        }

        Intent serviceIntent = new Intent(getApplicationContext(), TopAppDetectionService.class);
        getApplicationContext().startService(serviceIntent);

        whiteList = getWhiteListApps();
        Collections.sort(whiteList, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()));

        if (whiteList.size() > 0) {
            no_fua.setVisibility(View.GONE);
            rvWhiteApps.setVisibility(View.VISIBLE);
        } else {
            no_fua.setVisibility(View.VISIBLE);
            rvWhiteApps.setVisibility(View.GONE);
        }

        whiteListAdapter = new MyAppsAdapter(FUAActivity.this, whiteList, true, new MyAppsAdapter.ItemClicked() {
            @Override
            public void onCLick(AppList appList) {
                try {
                    Intent intent = getPackageManager().getLaunchIntentForPackage(appList.getPackages());
                    startActivity(intent);
                } catch (Exception e) {
                    Toast.makeText(FUAActivity.this, "Cannot open " + appList.getName(), Toast.LENGTH_SHORT).show();
                }
            }
        });

        rvWhiteApps.setLayoutManager(new GridLayoutManager(this, 4));
        rvWhiteApps.setAdapter(whiteListAdapter);

        if (!isFromDashboard) {
            // from settings page
            no_fua_txt.setText(R.string.no_frequently_used_apps);
            fua_sub_title.setVisibility(View.GONE);

            rvApps.setVisibility(View.VISIBLE);
            all_apps_title.setVisibility(View.VISIBLE);
            findViewById(R.id.done_btn).setVisibility(View.VISIBLE);

            adapter = new MyAppsAdapter(FUAActivity.this, getInstalledApps(), false, appList -> {
                if (!isContainsWhiteList(appList)) {
                    whiteList.add(appList);
                    Collections.sort(whiteList, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()));
                } else {
                    whiteList.remove(getPosition(appList));
                }

                if (whiteList.size() > 0) {
                    no_fua.setVisibility(View.GONE);
                    rvWhiteApps.setVisibility(View.VISIBLE);
                } else {
                    no_fua.setVisibility(View.VISIBLE);
                    rvWhiteApps.setVisibility(View.GONE);
                }

                whiteListAdapter.notifyDataSetChanged();
            });

            rvApps.setLayoutManager(new GridLayoutManager(this, 4));
            rvApps.setAdapter(adapter);
        } else {
            // from dashboard
            no_fua_txt.setText(R.string.no_frequently_used_apps_set_up);
            fua_sub_title.setVisibility(View.VISIBLE);

            rvApps.setVisibility(View.GONE);
            all_apps_title.setVisibility(View.GONE);
            findViewById(R.id.done_btn).setVisibility(View.GONE);

            LinearLayout.LayoutParams p1 = (LinearLayout.LayoutParams) no_fua.getLayoutParams();
            p1.weight = 10;
            no_fua.setLayoutParams(p1);

            LinearLayout.LayoutParams p2 = (LinearLayout.LayoutParams) rvWhiteApps.getLayoutParams();
            p2.weight =  10;
            rvWhiteApps.setLayoutParams(p2);
        }

        findViewById(R.id.done_btn).setOnClickListener(v -> {
            onBackPressed();
        });

        findViewById(R.id.back_btn).setOnClickListener(v -> {
            onBackPressed();
        });
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        final Configuration configuration = new Configuration(newBase.getResources().getConfiguration());
        configuration.fontScale = Math.min(configuration.fontScale, 1.1f);
        applyOverrideConfiguration(configuration);
        super.attachBaseContext(newBase);
    }

    private int getPosition(AppList appList) {
        for (int i = 0; i < whiteList.size(); i++) {
            if (whiteList.get(i).getPackages().equals(appList.getPackages())) {
                return i;
            }
        }
        return 0;
    }


    private boolean isContainsWhiteList(AppList appList) {
        for (AppList appList1 : whiteList) {
            if (appList.getPackages().equals(appList1.getPackages())) {
                return true;
            }
        }
        return false;
    }

    private List<AppList> getWhiteListApps() {
        ArrayList<AppList> appsList = new ArrayList<>();
        
        List<AppList> totalList = getInstalledApps();

        for (AppList list : totalList) {
            if (!isSelectedApp(list.getPackages())) {
                appsList.add(list);
            }
        }

        return appsList;
    }

    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;
    }

    @Override
    protected void onResume() {
        super.onResume();
//        swBlock.setChecked(isAccessibilityAppBlockingEnabled());
    }

    private List<AppList> getInstalledApps() {
        if (installed_app_list != null) return installed_app_list;

        PackageManager packageManager = getPackageManager();

        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);

        List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(intent, 0);
        ArrayList<String> appsName = new ArrayList<>();
        List<AppList> apps = new ArrayList<>();

        // Iterate over the resolved apps and extract their names
        for (ResolveInfo resolveInfo : resolveInfoList) {
            String appName1 = resolveInfo.loadLabel(packageManager).toString();
            Drawable icon = resolveInfo.loadIcon(packageManager);
            String packages = resolveInfo.activityInfo.packageName;
            apps.add(new AppList(appName1, icon, packages));
            appsName.add(packages);
        }

        Collections.sort(apps, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()));
        Collections.sort(appsName);

        if (mySharedPref.checkKey("APP_LIST")) {
            if (mySharedPref.getArrayList("APP_LIST").size() == 0) {
                mySharedPref.setArrayList("APP_LIST", appsName);
            }
        } else {
            // Aditya -> removing Basic apps from block list i.e. APP_LIST

            try {
                // Camera
                Intent camIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                ResolveInfo camInfo = packageManager.resolveActivity(camIntent, PackageManager.MATCH_DEFAULT_ONLY);
                if (camInfo != null){
                    appsName.remove(camInfo.activityInfo.packageName);
                }
            } catch (Exception e) {
                // do nothing
            }

            try {
                // Gallery
                Intent mainIntent = new Intent(Intent.ACTION_PICK);
                mainIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                List<ResolveInfo> galleryApps = getPackageManager().queryIntentActivities(mainIntent, PackageManager.GET_RESOLVED_FILTER);
                if (galleryApps != null && !galleryApps.isEmpty()) {
                    appsName.remove(galleryApps.get(0).activityInfo.packageName);
                }
            } catch (Exception e) {
                // do nothing
            }

            // SMS
            try {
                appsName.remove(Telephony.Sms.getDefaultSmsPackage(this));
            } catch (Exception e) {
                // do nothing
            }

            // CALL
            try {
                Intent dailIntent = new Intent(Intent.ACTION_DIAL);
                ResolveInfo dialInfo = getPackageManager().resolveActivity(dailIntent, PackageManager.MATCH_DEFAULT_ONLY);
                if (dialInfo != null) {
                    appsName.remove(dialInfo.activityInfo.packageName);
                }
            } catch (Exception e) {
                // do nothing
            }

            // maps
            try {
                Intent mapsIntent = new Intent(android.content.Intent.ACTION_VIEW,
                        Uri.parse("https://www.google.com/maps/dir/?api=1&destination=" + "19,20" + "&travelmode=walking"));

                ActivityInfo info = mapsIntent.resolveActivityInfo(getPackageManager(), 0);
                if (info != null && info.packageName != null){
                    appsName.remove(info.packageName);
                }

            }catch (Exception e){
                // do nothing
            }

            // settings app
            try {
                Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
                ActivityInfo settingsInfo = settingsIntent.resolveActivityInfo(getPackageManager(), 0);
                if (settingsInfo != null && settingsInfo.packageName != null){
                    appsName.remove(settingsInfo.packageName);
                }
            } catch (Exception e) {
                // do nothing
            }

            mySharedPref.setArrayList("APP_LIST", appsName);
        }

        return installed_app_list = apps;
    }

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

        try {
            accessibilityEnabled = Settings.Secure.getInt(
                    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(
                    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 boolean isSystemPackage(PackageInfo pkgInfo) {
        return (pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
    }

    private void openAccessibilityDialog() {

        AppUtil.showAlert(this,
                "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);
                    startActivity(accessibilityIntent);
                },
                "Cancel",(dialog, id) -> {
                    //  Action for 'NO' Button
                    dialog.cancel();
                });
    }

}