package com.atr.tedit.settings;

import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
//import android.support.v4.provider.DocumentFile;
import androidx.documentfile.provider.DocumentFile;
import android.util.Log;

import com.atr.tedit.TEditActivity;
import com.atr.tedit.file.AndPath;
import com.atr.tedit.file.descriptor.AndFile;
import com.atr.tedit.util.FontUtil;

import java.util.Arrays;

/**
 * @author Adam T. Ryder
 * <a href="https://www.inventati.org/1337gallery">https://www.inventati.org/1337gallery</a>
 */

public class Settings {
    public static final int TEXTDIR_LTR = 0;
    public static final int TEXTDIR_RTL = 1;

    public static final int AOB_CLOSE = 0;
    public static final int AOB_PARENT = 1;

    public static final int THEME_LIGHT = 0;
    public static final int THEME_DARK = 1;
    public static final int THEME_BLACK = 2;

    public static final int AOS_ASK = 0;
    public static final int AOS_FILE = 1;
    public static final int AOS_CONTENT = 2;

    private static AndPath startupPath;

    private static boolean saveHistory = false;
    private static final AndFile[] history = new AndFile[10];

    private static int actionOnBack = AOB_PARENT;
    private static int actionOnShare = AOS_ASK;
    private static boolean enableRoot = false;

    private static boolean wordWrap = true;
    private static boolean lineNumbers = false;
    private static int systemTextDirection = TEXTDIR_LTR;
    private static int editorTextDirection = TEXTDIR_LTR;

    private static int theme = 0;

    private static boolean showPermitHelp = true;
    private static boolean firstRun = true;

    public static AndPath getStartupPath() { return startupPath == null ? null : startupPath.clone(); }

    public static void setStartupPath(AndPath path) {
        startupPath = path;
    }

    public static boolean isSaveHistory() {
        return saveHistory;
    }

    public static void setSaveHistory(boolean save) {
        saveHistory = save;
    }

    public static AndFile[] getHistory() {
        return history;
    }

    public static void addToHistory(AndFile file, TEditActivity ctx) {
        if (!isSaveHistory() || file == null)
            return;

        int nullIdx = -1;
        int duplicateIdx = -1;
        for (int i = 0; i < history.length; i++) {
            if (history[i] == null) {
                if (nullIdx < 0)
                    nullIdx = i;
            } else if (history[i].getPath().equals(file.getPath()))
                duplicateIdx = i;
        }

        if (duplicateIdx >= 0) {
            nullIdx = duplicateIdx;
        } else if (nullIdx < 0)
            nullIdx = history.length - 1;

        for (int i = nullIdx; i >= 1; i--) {
            history[i] = history[i - 1];
        }
        history[0] = file;
        saveHistory(ctx);
    }

    public static boolean isWordWrap() {
        return wordWrap;
    }

    protected static void setWordWrap(boolean wrap) {
        wordWrap = wrap;
    }

    public static boolean isShowLineNumbers() { return lineNumbers; }

    protected static void setShowLineNumbers(boolean show) {
        lineNumbers = show;
    }

    public static int getSystemTextDirection() {
        return systemTextDirection;
    }

    protected static void setSystemTextDirection(int direction) {
        systemTextDirection = (direction > TEXTDIR_RTL) ? TEXTDIR_RTL : (direction < TEXTDIR_LTR) ? TEXTDIR_LTR : direction;
    }

    public static int getActionOnBack() {
        return actionOnBack;
    }

    protected static void setActionOnBack(int aob) {
        actionOnBack = (aob > AOB_PARENT) ? AOB_PARENT : (aob < AOB_CLOSE) ? AOB_CLOSE : aob;
    }

    public static int getActionOnShare() { return actionOnShare; }

    public static void setActionOnShare(int aos) {
        actionOnShare = (aos > AOS_CONTENT) ? AOS_CONTENT : (aos < AOS_ASK) ? AOS_ASK : aos;
    }

    public static boolean isEnableRoot() { return enableRoot; }

    public static void setEnableRoot(boolean enable) { enableRoot = enable; }

    public static boolean isShowPermitHelp() {
        return showPermitHelp;
    }

    public static void setShowPermitHelp(boolean show) {
        showPermitHelp = show;
    }

    public static int getEditorTextDirection() {
        return editorTextDirection;
    }

    protected static void setEditorTextDirection(int direction) {
        editorTextDirection = (direction > TEXTDIR_RTL) ? TEXTDIR_RTL : (direction < TEXTDIR_LTR) ? TEXTDIR_LTR : direction;
    }

    public static int getTheme() {
        return theme;
    }

    public static void setTheme(int newTheme) {
        theme = (newTheme < 0) ? 0 : (newTheme > 2) ? 2 : newTheme;
    }

    public static void loadSettings(final TEditActivity ctx) {
        SharedPreferences prefs = ctx.getSharedPreferences(ctx.getPackageName(), ctx.MODE_PRIVATE);

        String startupJson = prefs.getString("startupPath", "");
        if (startupJson.equals("null") || startupJson.isEmpty()) {
            startupPath = null;
        } else {
            try {
                startupPath = AndPath.fromJson(ctx, prefs.getString("startupPath", ""));
            } catch (Exception e) {
                startupPath = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) ? null : ctx.getCurrentPath().clone();
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && startupPath != null) {
                Uri[] uris = ctx.getPermittedUris();
                boolean found = false;
                for (int i = 0; i < uris.length; i++) {
                    if (((DocumentFile) startupPath.getRoot().getFile()).getUri().toString().startsWith(uris[i].toString())) {
                        found = true;
                        break;
                    }
                }

                if (!found)
                    startupPath = null;
            }
        }

        saveHistory = prefs.getBoolean("enableHistory", false);
        wordWrap = prefs.getBoolean("wordWrap", true);
        lineNumbers = prefs.getBoolean("lineNumbers", false);
        systemTextDirection = prefs.getInt("systemTextDirection", TEXTDIR_LTR);
        editorTextDirection = prefs.getInt("editorTextDirection", TEXTDIR_LTR);
        theme = prefs.getInt("editorTheme", THEME_LIGHT);

        FontUtil.setSystemTypeface(prefs.getString("systemTypeface", "montserratalternates_regular"));
        FontUtil.setEditorTypeface(prefs.getString("editorTypeface", "metropolis_regular"));
        FontUtil.setEditorSize(prefs.getInt("editorFontSize", 15));

        actionOnBack = prefs.getInt("actionOnBack", AOB_PARENT);
        actionOnShare = prefs.getInt("actionOnShare", AOS_ASK);
        enableRoot = prefs.getBoolean("enableRoot", false);

        if (saveHistory) {
            StringBuilder sb = new StringBuilder("recentDocument_0");
            for (int i = 0; i < history.length; i++) {
                sb.deleteCharAt(sb.length() - 1);
                sb.append(i);
                String path = prefs.getString(sb.toString(), "");
                AndFile recentDocument = null;
                if (!path.isEmpty())
                    recentDocument = AndFile.createDescriptor(path, ctx);

                history[i] = (recentDocument == null) ? null : recentDocument;
            }
        }

        showPermitHelp = prefs.getBoolean("showPermitHelp", true);
    }

    public static void saveSettings(final TEditActivity ctx) {
        SharedPreferences.Editor prefs = ctx.getSharedPreferences(ctx.getPackageName(), ctx.MODE_PRIVATE).edit();

        prefs.putString("startupPath", startupPath == null ? "null" : startupPath.toJson());
        prefs.putBoolean("enableHistory", saveHistory);
        prefs.putBoolean("wordWrap", wordWrap);
        prefs.putBoolean("lineNumbers", lineNumbers);
        prefs.putInt("systemTextDirection", systemTextDirection);
        prefs.putInt("editorTextDirection", editorTextDirection);
        prefs.putInt("editorTheme", theme);
        prefs.putString("systemTypeface", FontUtil.getSystemPath());
        prefs.putString("editorTypeface", FontUtil.getEditorPath());
        prefs.putInt("editorFontSize", FontUtil.getEditorSize());
        prefs.putInt("editorFontSize", FontUtil.getEditorSize());
        prefs.putInt("actionOnBack", actionOnBack);
        prefs.putInt("actionOnShare", actionOnShare);
        prefs.putBoolean("enableRoot", enableRoot);

        prefs.putBoolean("showPermitHelp", showPermitHelp);

        prefs.apply();
    }

    public static void saveHistory(final TEditActivity ctx) {
        SharedPreferences.Editor prefs = ctx.getSharedPreferences(ctx.getPackageName(), ctx.MODE_PRIVATE).edit();

        StringBuilder sb = new StringBuilder("recentDocument_0");
        for (int i = 0; i < history.length; i++) {
            sb.deleteCharAt(sb.length() - 1);
            sb.append(i);
            AndFile recentDocument = history[i];
            prefs.putString(sb.toString(), recentDocument == null ? "" : recentDocument.getPathIdentifier());
        }

        prefs.apply();
    }

    public static void clearHistory(final TEditActivity ctx) {
        Arrays.fill(history, null);
        saveHistory(ctx);
    }

    public static boolean isFirstRun(final TEditActivity ctx) {
        if (!firstRun)
            return false;

        firstRun = false;
        SharedPreferences prefs = ctx.getSharedPreferences(ctx.getPackageName(), ctx.MODE_PRIVATE);
        long lastVer = prefs.getLong("longVersion", -1);
        if (lastVer < 0)
            lastVer = prefs.getInt("version", 0);
        long currentVer = 0;
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                currentVer = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES).getLongVersionCode();
            } else
                currentVer = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES).versionCode;
        } catch (Exception e) {
            Log.w("TEdit Settings:", "Unable to assertain current version: " + e.getMessage());
            currentVer = 19;
        }
        return lastVer < currentVer;
    }

    public static void saveVer(final TEditActivity ctx) {
        SharedPreferences.Editor prefs = ctx.getSharedPreferences(ctx.getPackageName(), ctx.MODE_PRIVATE).edit();
        long currentVer = 0;
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                currentVer = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES).getLongVersionCode();
            } else
                currentVer = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES).versionCode;
        } catch (Exception e) {
            Log.w("TEdit Settings:", "Unable to assertain current version: " + e.getMessage());
            currentVer = 19;
        }
        prefs.putLong("longVersion", currentVer);
        prefs.apply();
        firstRun = false;
    }
}
