package com.example.modifier;

import static com.example.modifier.utils.SystemKt.getContext;

import android.accounts.AccountManager;
import android.accounts.AuthenticatorDescription;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.util.Log;

import com.google.android.material.button.MaterialButton;
import com.google.android.material.progressindicator.CircularProgressIndicatorSpec;
import com.google.android.material.progressindicator.IndeterminateDrawable;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.xmlpull.v1.XmlPullParser;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;

public class Utils {

    public static void makeLoadingButton(Context context, MaterialButton button) {
        CircularProgressIndicatorSpec spec = new CircularProgressIndicatorSpec(context, null, 0,
                com.google.android.material.R.style.Widget_Material3_CircularProgressIndicator_ExtraSmall);
        IndeterminateDrawable progressIndicatorDrawable = IndeterminateDrawable.createCircularDrawable(context, spec);
        button.setIcon(progressIndicatorDrawable);
        button.setEnabled(false);
    }

    public static boolean copyAssetFolder(AssetManager assetManager,
                                          String fromAssetPath, String toPath) {
        try {
            String[] files = assetManager.list(fromAssetPath);
            new File(toPath).mkdirs();
            boolean res = true;
            for (String file : files)
                if (file.contains("."))
                    res &= copyAsset(assetManager,
                            fromAssetPath + "/" + file,
                            toPath + "/" + file);
                else
                    res &= copyAssetFolder(assetManager,
                            fromAssetPath + "/" + file,
                            toPath + "/" + file);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean copyAsset(AssetManager assetManager,
                                    String fromAssetPath, String toPath) {
        if (new File(toPath).exists())
            return true;
        InputStream in = null;
        OutputStream out = null;
        try {
            in = assetManager.open(fromAssetPath);
            new File(toPath).createNewFile();
            out = Files.newOutputStream(Paths.get(toPath));
            IOUtils.copy(in, out);
            in.close();
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static int dp2px(Context context, int dp) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    public static void startPreferenceActivity(String type) {
        Context context = getContext();
        AccountManager accountManager = AccountManager.get(context);
        AuthenticatorDescription[] descriptions = accountManager.getAuthenticatorTypes();
        AuthenticatorDescription neededDescription = null;
        for (AuthenticatorDescription description : descriptions) {
            if (description.type.equals(type)) {
                neededDescription = description;
                break;
            }
        }
        if (neededDescription != null) {
            String packageName = neededDescription.packageName;
            int prefsId = neededDescription.accountPreferencesId;
            try {
                Resources resources = context.getPackageManager().getResourcesForApplication(packageName);
                XmlResourceParser xpp = resources.getLayout(prefsId);
                xpp.next();
                String action = null;
                String targetPackage = packageName; //default to the account pref package name...?
                String targetClass = null;
                int eventType = xpp.getEventType();
                while (eventType != XmlPullParser.END_DOCUMENT) {
                    if (eventType == XmlPullParser.START_TAG) {
                        if (xpp.getName().equals("intent")) {
                            int count = xpp.getAttributeCount();
                            for (int i = 0; i < count; i++) {
                                String name = xpp.getAttributeName(i);
                                if (name.equals("action")) {
                                    action = xpp.getAttributeValue(i);
                                } else if (name.equals("targetPackage")) {
                                    targetPackage = xpp.getAttributeValue(i);
                                } else if (name.equals("targetClass")) {
                                    targetClass = xpp.getAttributeValue(i);
                                }
                            }
                        }
                    }
                    eventType = xpp.next();
                }
                if (action != null) {
                    context.startActivity(new Intent(action));
                } else if (targetClass != null) {
                    context.startActivity(new Intent(context.createPackageContext(targetPackage, Context.CONTEXT_IGNORE_SECURITY), Class.forName(targetClass)));
                }
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
