import { Color } from '../color';
import { numberHasDecimals, numberIs64Bit } from './types';
import { getNativeApp } from '../application/helpers-common';
import { androidGetCurrentActivity } from '../application/helpers';
import { Trace } from '../trace';
import { topmost } from '../ui/frame/frame-stack';
export function dataDeserialize(nativeData) {
    if (nativeData === null || typeof nativeData !== 'object') {
        return nativeData;
    }
    let store;
    switch (nativeData.getClass().getName()) {
        case 'java.lang.String': {
            return String(nativeData);
        }
        case 'java.lang.Boolean': {
            return String(nativeData) === 'true';
        }
        case 'java.lang.Float':
        case 'java.lang.Integer':
        case 'java.lang.Long':
        case 'java.lang.Double':
        case 'java.lang.Short': {
            return Number(nativeData);
        }
        case 'org.json.JSONArray': {
            store = [];
            for (let j = 0; j < nativeData.length(); j++) {
                store[j] = dataDeserialize(nativeData.get(j));
            }
            break;
        }
        case 'org.json.JSONObject': {
            store = {};
            const i = nativeData.keys();
            let key;
            while (i.hasNext()) {
                key = i.next();
                store[key] = dataDeserialize(nativeData.get(key));
            }
            break;
        }
        case 'androidx.collection.SimpleArrayMap': {
            const count = nativeData.size();
            for (let l = 0; l < count; l++) {
                const key = nativeData.keyAt(l);
                store[key] = dataDeserialize(nativeData.get(key));
            }
            break;
        }
        case 'androidx.collection.ArrayMap':
        case 'android.os.Bundle':
        case 'java.util.HashMap':
        case 'java.util.Map': {
            store = {};
            const keys = nativeData.keySet().toArray();
            for (let k = 0; k < keys.length; k++) {
                const key = keys[k];
                store[key] = dataDeserialize(nativeData.get(key));
            }
            break;
        }
        default:
            if (typeof nativeData === 'object' && nativeData instanceof java.util.List) {
                const array = [];
                const size = nativeData.size();
                for (let i = 0, n = size; i < n; i++) {
                    array[i] = dataDeserialize(nativeData.get(i));
                }
                store = array;
            }
            else {
                store = null;
            }
            break;
    }
    return store;
}
export function dataSerialize(data, wrapPrimitives) {
    let store;
    switch (typeof data) {
        case 'string':
        case 'boolean': {
            if (wrapPrimitives) {
                if (typeof data === 'string') {
                    return new java.lang.String(data);
                }
                return new java.lang.Boolean(data);
            }
            return data;
        }
        case 'number': {
            const hasDecimals = numberHasDecimals(data);
            if (numberIs64Bit(data)) {
                if (hasDecimals) {
                    return java.lang.Double.valueOf(data);
                }
                else {
                    return java.lang.Long.valueOf(data);
                }
            }
            else {
                if (hasDecimals) {
                    return java.lang.Float.valueOf(data);
                }
                else {
                    return java.lang.Integer.valueOf(data);
                }
            }
        }
        case 'object': {
            if (!data) {
                return null;
            }
            if (data instanceof Date) {
                return new java.util.Date(data.getTime());
            }
            if (Array.isArray(data)) {
                store = new java.util.ArrayList();
                data.forEach((item) => store.add(dataSerialize(item, wrapPrimitives)));
                return store;
            }
            if (data.native) {
                return data.native;
            }
            store = new java.util.HashMap();
            Object.keys(data).forEach((key) => store.put(key, dataSerialize(data[key], wrapPrimitives)));
            return store;
        }
        default:
            return null;
    }
}
export function getApplicationContext() {
    return getApplication().getApplicationContext();
}
export function getCurrentActivity() {
    return androidGetCurrentActivity();
}
export function getApplication() {
    return getNativeApp();
}
export function getResources() {
    return getApplication().getResources();
}
let packageName;
export function getPackageName() {
    if (!packageName) {
        packageName = getApplicationContext().getPackageName();
    }
    return packageName;
}
let inputMethodManager;
export function getInputMethodManager() {
    if (!inputMethodManager) {
        inputMethodManager = getApplicationContext().getSystemService(android.content.Context.INPUT_METHOD_SERVICE);
    }
    return inputMethodManager;
}
export function getWindow() {
    return getCurrentActivity()?.getWindow();
}
export function showSoftInput(nativeView) {
    const inputManager = getInputMethodManager();
    if (inputManager && nativeView instanceof android.view.View) {
        inputManager.showSoftInput(nativeView, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT);
    }
}
export function dismissSoftInput(nativeView) {
    const inputManager = getInputMethodManager();
    let windowToken;
    if (nativeView instanceof android.view.View) {
        if (!nativeView.hasFocus()) {
            return;
        }
        windowToken = nativeView.getWindowToken();
    }
    else if (getCurrentActivity() instanceof androidx.appcompat.app.AppCompatActivity) {
        const modalDialog = (topmost()?._modalParent ?? topmost()?.modal)?._dialogFragment?.getDialog();
        const window = (modalDialog ?? getCurrentActivity()).getWindow();
        const decorView = window.getDecorView();
        if (decorView) {
            windowToken = decorView.getWindowToken();
            decorView.requestFocus();
        }
        else {
            windowToken = null;
        }
    }
    if (inputManager && windowToken) {
        inputManager.hideSoftInputFromWindow(windowToken, 0);
    }
}
export var collections;
(function (collections) {
    function stringArrayToStringSet(str) {
        const hashSet = new java.util.HashSet();
        if (str !== undefined) {
            for (const element in str) {
                hashSet.add('' + str[element]);
            }
        }
        return hashSet;
    }
    collections.stringArrayToStringSet = stringArrayToStringSet;
    function stringSetToStringArray(stringSet) {
        const arr = [];
        if (stringSet !== undefined) {
            const it = stringSet.iterator();
            while (it.hasNext()) {
                const element = '' + it.next();
                arr.push(element);
            }
        }
        return arr;
    }
    collections.stringSetToStringArray = stringSetToStringArray;
})(collections || (collections = {}));
export var resources;
(function (resources_1) {
    let attr;
    const attrCache = new Map();
    function getDrawableId(name) {
        return getId(':drawable/' + name);
    }
    resources_1.getDrawableId = getDrawableId;
    function getStringId(name) {
        return getId(':string/' + name);
    }
    resources_1.getStringId = getStringId;
    function getId(name) {
        const resources = getResources();
        const packageName = getPackageName();
        const uri = packageName + name;
        return resources.getIdentifier(uri, null, null);
    }
    resources_1.getId = getId;
    function getResource(name, type) {
        return getResources().getIdentifier(name, type, getPackageName());
    }
    resources_1.getResource = getResource;
    function getPaletteColor(name, context) {
        if (attrCache.has(name)) {
            return attrCache.get(name);
        }
        let result = 0;
        try {
            if (!attr) {
                attr = java.lang.Class.forName('androidx.appcompat.R$attr');
            }
            let colorID = 0;
            const field = attr.getField(name);
            if (field) {
                colorID = field.getInt(null);
            }
            if (colorID) {
                const typedValue = new android.util.TypedValue();
                context.getTheme().resolveAttribute(colorID, typedValue, true);
                result = typedValue.data;
            }
        }
        catch (ex) {
            Trace.write('Cannot get pallete color: ' + name, Trace.categories.Error, Trace.messageType.error);
        }
        attrCache.set(name, result);
        return result;
    }
    resources_1.getPaletteColor = getPaletteColor;
})(resources || (resources = {}));
export function isRealDevice() {
    const fingerprint = android.os.Build.FINGERPRINT;
    return fingerprint != null && (fingerprint.indexOf('vbox') > -1 || fingerprint.indexOf('generic') > -1);
}
const DefaultLightScrim = new Color(0xe6, 0xff, 0xff, 0xff);
const DefaultDarkScrim = new Color(0x80, 0x1b, 0x1b, 0x1b);
const DefaultStatusBarLight = new Color(0);
const DefaultStatusBarDark = new Color(0);
const systemColors = new WeakMap();
function setEnableEdgeToEdge(activity, existingColors) {
    enableEdgeToEdge(activity, {
        statusBarLightColor: existingColors.statusBarLight,
        statusBarDarkColor: existingColors.statusBarDark,
        navigationBarLightColor: existingColors.navigationBarLight,
        navigationBarDarkColor: existingColors.navigationBarDark,
        handleDarkMode: existingColors?.handler ?? null,
    });
}
export function setStatusBarColor(options) {
    const statusBarLightColor = options?.lightColor ?? null;
    const statusBarDarkColor = options?.darkColor ?? null;
    const activity = options?.activity ?? getCurrentActivity();
    if (activity) {
        const existingColors = systemColors.get(activity) ?? {
            navigationBarLight: DefaultLightScrim,
            navigationBarDark: DefaultDarkScrim,
            statusBarLight: DefaultStatusBarLight,
            statusBarDark: DefaultStatusBarDark,
        };
        existingColors.statusBarLight ?? (existingColors.statusBarLight = statusBarLightColor);
        existingColors.statusBarDark ?? (existingColors.statusBarDark = statusBarDarkColor);
        systemColors.set(getCurrentActivity(), existingColors);
        setEnableEdgeToEdge(activity, existingColors);
    }
}
export function setNavigationBarColor(options) {
    const navigationBarLightColor = options?.lightColor ?? null;
    const navigationBarDarkColor = options?.darkColor ?? null;
    const activity = options?.activity ?? getCurrentActivity();
    if (activity) {
        const existingColors = systemColors.get(activity) ?? {
            navigationBarLight: DefaultLightScrim,
            navigationBarDark: DefaultDarkScrim,
            statusBarLight: DefaultStatusBarLight,
            statusBarDark: DefaultStatusBarDark,
        };
        existingColors.navigationBarLight ?? (existingColors.navigationBarLight = navigationBarLightColor);
        existingColors.navigationBarDark ?? (existingColors.navigationBarDark = navigationBarDarkColor);
        systemColors.set(getCurrentActivity(), existingColors);
        setEnableEdgeToEdge(activity, existingColors);
    }
}
export function setDarkModeHandler(options) {
    const darkModeHandler = options?.handler ?? null;
    const activity = options?.activity ?? getCurrentActivity();
    if (activity) {
        const existingColors = systemColors.get(activity) ?? {
            navigationBarLight: DefaultLightScrim,
            navigationBarDark: DefaultDarkScrim,
            statusBarLight: DefaultStatusBarLight,
            statusBarDark: DefaultStatusBarDark,
        };
        existingColors.handler ?? (existingColors.handler = darkModeHandler);
        systemColors.set(getCurrentActivity(), existingColors);
        setEnableEdgeToEdge(activity, existingColors);
    }
}
export function enableEdgeToEdge(activity, windowOrOptions, options) {
    let handleDarkMode;
    let statusBarLight = 0;
    let statusBarDark = 0;
    let navigationBarLight = DefaultLightScrim.android;
    let navigationBarDark = DefaultDarkScrim.android;
    let opts = windowOrOptions;
    let isWindow = false;
    if (windowOrOptions instanceof android.view.Window) {
        opts = options;
        isWindow = true;
    }
    if (opts) {
        if (typeof opts.handleDarkMode === 'function') {
            handleDarkMode = new org.nativescript.widgets.Utils.HandleDarkMode({
                onHandle(bar, resources) {
                    if (bar === 0) {
                        return opts.handleDarkMode('status', resources);
                    }
                    else {
                        return opts.handleDarkMode('navigation', resources);
                    }
                },
            });
        }
        if (opts.statusBarLightColor instanceof Color) {
            statusBarLight = opts.statusBarLightColor.android;
        }
        if (opts.statusBarDarkColor instanceof Color) {
            statusBarDark = opts.statusBarDarkColor.android;
        }
        if (opts.navigationBarLightColor instanceof Color) {
            navigationBarLight = opts.navigationBarLightColor.android;
        }
        if (opts.navigationBarDarkColor instanceof Color) {
            navigationBarDark = opts.navigationBarDarkColor.android;
        }
    }
    if (handleDarkMode) {
        if (isWindow) {
            org.nativescript.widgets.Utils.enableEdgeToEdge(activity, windowOrOptions, handleDarkMode);
        }
        else {
            org.nativescript.widgets.Utils.enableEdgeToEdge(activity, java.lang.Integer.valueOf(statusBarLight), java.lang.Integer.valueOf(statusBarDark), java.lang.Integer.valueOf(navigationBarLight), java.lang.Integer.valueOf(navigationBarDark), handleDarkMode);
        }
    }
    else {
        if (isWindow) {
            org.nativescript.widgets.Utils.enableEdgeToEdge(activity, windowOrOptions);
        }
        else {
            org.nativescript.widgets.Utils.enableEdgeToEdge(activity, java.lang.Integer.valueOf(statusBarLight), java.lang.Integer.valueOf(statusBarDark), java.lang.Integer.valueOf(navigationBarLight), java.lang.Integer.valueOf(navigationBarDark));
        }
    }
}
export function getIgnoreEdgeToEdgeOnOlderDevices() {
    return org.nativescript.widgets.Utils.ignoreEdgeToEdgeOnOlderDevices;
}
export function setIgnoreEdgeToEdgeOnOlderDevices(value) {
    org.nativescript.widgets.Utils.ignoreEdgeToEdgeOnOlderDevices = value;
}
//# sourceMappingURL=native-helper-for-android.js.map