import { parseVersion } from './version.js';
import { applyRules } from './rules.js';

function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
        });
    }
    return target;
}
var _match_, _match_1;
const RULES = {
    // BROWSER ==========================================================================
    browser: [
        // WEBVIEW ------------------------------------------------------------------------
        // iTunes/Music.app/TV.app
        [
            /^(itunes|music|tv)\/([\w.]+)\s/i,
            (match)=>_object_spread_props(_object_spread({
                    name: 'webview',
                    variant: match[1].trim().toLowerCase().replace(/(music|tv)/i, '$1.app')
                }, parseVersion(match[2])), {
                    mobile: false
                })
        ],
        // Facebook
        [
            /(?:(?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w.]+);)/i,
            (match)=>_object_spread({
                    name: 'webview',
                    variant: 'facebook',
                    mobile: true
                }, parseVersion(match[1]))
        ],
        // Instagram / SnapChat
        [
            /(instagram|snapchat)[/ ]([-\w.]+)/i,
            (match)=>_object_spread({
                    name: 'webview',
                    variant: match[1].trim().toLowerCase(),
                    mobile: true
                }, parseVersion(match[2]))
        ],
        // TikTok
        [
            /musical_ly(?:.+app_?version\/|_)([\w.]+)/i,
            (match)=>_object_spread({
                    name: 'webview',
                    variant: 'tiktok',
                    mobile: true
                }, parseVersion(match[1]))
        ],
        // Twitter
        [
            /twitter/i,
            ()=>({
                    name: 'webview',
                    variant: 'twitter',
                    mobile: true
                })
        ],
        // Chrome WebView
        [
            / wv\).+?(?:version|chrome)\/([\w.]+)/i,
            (match)=>_object_spread({
                    name: 'webview',
                    mobile: true
                }, parseVersion(match[1]))
        ],
        // ELECTRON -----------------------------------------------------------------------
        [
            /electron\/([\w.]+) safari/i,
            (match)=>_object_spread({
                    name: 'electron',
                    mobile: false
                }, parseVersion(match[1]))
        ],
        // OTHER --------------------------------------------------------------------------
        [
            /tesla\/(.*?(20\d\d\.([-\w.])+))/i,
            (match)=>_object_spread_props(_object_spread({
                    name: 'other',
                    variant: 'tesla',
                    mobile: false
                }, parseVersion(match[2])), {
                    version: match[1]
                })
        ],
        [
            /(samsung|huawei)browser\/([-\w.]+)/i,
            (match)=>_object_spread({
                    name: 'other',
                    variant: match[1].trim().toLowerCase().replace(/browser/i, ''),
                    mobile: true
                }, parseVersion(match[2]))
        ],
        [
            /yabrowser\/([-\w.]+)/i,
            (match)=>_object_spread({
                    name: 'other',
                    variant: 'yandex',
                    mobile: false
                }, parseVersion(match[1]))
        ],
        [
            /(brave|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w.]+)/i,
            (match, { userAgent })=>_object_spread({
                    name: 'other',
                    variant: match[1].trim().toLowerCase(),
                    mobile: /mobile/i.test(userAgent)
                }, parseVersion(match[2].replace(/-/g, '.')))
        ],
        // EDGE / IE ----------------------------------------------------------------------
        [
            /edg(e|ios|a)?\/([\w.]+)/i,
            (match)=>_object_spread({
                    name: 'edge',
                    mobile: /(edgios|edga)/i.test((_match_ = match[1]) !== null && _match_ !== void 0 ? _match_ : '')
                }, parseVersion(match[2]))
        ],
        [
            /trident.+rv[: ]([\w.]{1,9})\b.+like gecko/i,
            (match)=>_object_spread({
                    name: 'ie',
                    mobile: false
                }, parseVersion(match[1]))
        ],
        // OPERA --------------------------------------------------------------------------
        [
            /opr\/([\w.]+)/i,
            /opera mini\/([-\w.]+)/i,
            /opera [mobiletab]{3,6}\b.+version\/([-\w.]+)/i,
            /opera(?:.+version\/|[/ ]+)([\w.]+)/i,
            (match)=>_object_spread({
                    name: 'opera',
                    mobile: /mobile/i.test(match[0])
                }, parseVersion(match[1]))
        ],
        // CHROME -------------------------------------------------------------------------
        // Headless
        [
            /headlesschrome(?:\/([\w.]+)| )/i,
            (match)=>_object_spread({
                    name: 'chrome',
                    variant: 'headless',
                    mobile: false
                }, parseVersion(match[1]))
        ],
        // Chrome for iOS
        [
            /\b(?:crmo|crios)\/([\w.]+)/i,
            (match)=>_object_spread({
                    name: 'chrome',
                    mobile: true
                }, parseVersion(match[1]))
        ],
        // Chrome
        [
            /chrome(?: browser)?\/v?([\w.]+)( mobile)?/i,
            (match)=>_object_spread({
                    name: 'chrome',
                    mobile: /mobile/i.test((_match_1 = match[2]) !== null && _match_1 !== void 0 ? _match_1 : '')
                }, parseVersion(match[1]))
        ],
        // FIREFOX ------------------------------------------------------------------------
        // Focus
        [
            /\bfocus\/([\w.]+)/i,
            (match)=>_object_spread({
                    name: 'firefox',
                    variant: 'focus',
                    mobile: true
                }, parseVersion(match[1]))
        ],
        // Firefox for iOS
        [
            /fxios\/([\w.-]+)/i,
            /(?:mobile|tablet);.*(?:firefox)\/([\w.-]+)/i,
            (match)=>_object_spread({
                    name: 'firefox',
                    mobile: true
                }, parseVersion(match[1]))
        ],
        // Firefox OSS versions
        [
            /(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[/ ]?([\w.+]+)/i,
            (match)=>_object_spread({
                    name: 'firefox',
                    variant: match[1].trim().toLowerCase(),
                    mobile: false
                }, parseVersion(match[2]))
        ],
        // Firefox
        [
            /(?:firefox)\/([\w.]+)/i,
            /(?:mozilla)\/([\w.]+) .+rv:.+gecko\/\d+/i,
            (match)=>_object_spread({
                    name: 'firefox',
                    mobile: false
                }, parseVersion(match[1]))
        ],
        // SAFARI -------------------------------------------------------------------------
        [
            /version\/([\w.,]+) .*mobile(?:\/\w+ | ?)safari/i,
            /version\/([\w.,]+) .*(safari)/i,
            /webkit.+?(?:mobile ?safari|safari)(?:\/([\w.]+))/i,
            (match)=>_object_spread({
                    name: 'safari',
                    mobile: /mobile/i.test(match[0])
                }, parseVersion(match[1]))
        ]
    ],
    // ENGINE ---------------------------------------------------------------------------
    engine: [
        [
            /webkit\/(?:537\.36).+chrome\/(?!27)([\w.]+)/i,
            (match)=>_object_spread({
                    name: 'blink'
                }, parseVersion(match[1]))
        ],
        [
            /windows.+ edge\/([\w.]+)/i,
            (match)=>_object_spread({
                    name: 'blink'
                }, parseVersion(match[1]))
        ],
        [
            /presto\/([\w.]+)/i,
            (match)=>_object_spread({
                    name: 'presto'
                }, parseVersion(match[2]))
        ],
        [
            /trident\/([\w.]+)/i,
            (match)=>_object_spread({
                    name: 'trident'
                }, parseVersion(match[1]))
        ],
        [
            /gecko\/([\w.]+)/i,
            (match)=>_object_spread({
                    name: 'gecko'
                }, parseVersion(match[1]))
        ],
        [
            /(khtml|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w.]+)/i,
            (match)=>_object_spread({
                    name: 'other'
                }, parseVersion(match[2]))
        ],
        [
            /webkit\/([\w.]+)/i,
            (match)=>_object_spread({
                    name: 'webkit'
                }, parseVersion(match[1]))
        ]
    ],
    // OS -------------------------------------------------------------------------------
    os: [
        // Windows
        [
            /microsoft windows (vista|xp)/i,
            /windows nt 6\.2; (arm)/i,
            /windows (?:phone(?: os)?|mobile)[/ ]?([\d.\w ]*)/i,
            /windows[/ ]?([ntce\d. ]+\w)(?!.+xbox)/i,
            /(?:win(?=3|9|n)|win 9x )([nt\d.]+)/i,
            (match)=>_object_spread({
                    name: 'windows'
                }, parseVersion(match[1]))
        ],
        // iOS (iPhone/iPad)
        [
            /ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,
            /(?:ios;fbsv\/|iphone.+ios[/ ])([\d.]+)/i,
            (match)=>_object_spread({
                    name: 'ios'
                }, parseVersion(match[1].replace(/_/g, '.')))
        ],
        // macOS
        [
            /mac(?:intosh;?)? os x ?([\d._]+)/i,
            (match)=>_object_spread({
                    name: 'macos'
                }, parseVersion(match[1].replace(/_/g, '.')))
        ],
        // ChromeOS
        [
            /cros [\w]+(?:\)| ([\w.]+)\b)/i,
            (match)=>_object_spread({
                    name: 'chromeos'
                }, parseVersion(match[1]))
        ],
        // Android
        [
            /(?:android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-/ ]?([\w.]*)/i,
            /droid ([\w.]+|[\d+])\b.+(android[- ]x86|harmonyos)/i,
            (match)=>_object_spread({
                    name: 'android'
                }, parseVersion(match[1]))
        ],
        // Linux
        [
            /linux/i,
            ()=>({
                    name: 'linux'
                })
        ]
    ]
};
/**
 * Extend a data structure by running a list of functions over it.
 */ function applyExtensions(data, extensions) {
    let result = data;
    for (const extension of extensions){
        result = extension(result);
    }
    return result;
}
/**
 * Parse the user agent string from the navigator object into a descriptor.
 *
 * @param navigator The Navigator object to parse
 * @param options Parse options
 * @returns The descriptor with optional extensions applied
 */ function parseUserAgent(navigator, options) {
    var _navigator, _options;
    var _navigator_userAgent;
    const descriptor = {
        navigator: navigator,
        ua: (_navigator_userAgent = (_navigator = navigator) === null || _navigator === void 0 ? void 0 : _navigator.userAgent) !== null && _navigator_userAgent !== void 0 ? _navigator_userAgent : '',
        extensions: [],
        browser: applyRules(RULES.browser, navigator, {
            name: 'unknown',
            mobile: false
        }),
        engine: applyRules(RULES.engine, navigator, {
            name: 'unknown'
        }),
        os: applyRules(RULES.os, navigator, {
            name: 'unknown'
        })
    };
    var _options_extensions;
    return applyExtensions(descriptor, (_options_extensions = (_options = options) === null || _options === void 0 ? void 0 : _options.extensions) !== null && _options_extensions !== void 0 ? _options_extensions : []);
}

export { parseUserAgent };
