export const setLanguage = (selectedLanguage: string, i18n: any) => {
    // Locales and languages in arrays to match them
    const locales = ['en-US', 'es-ES', 'nl-NL', 'pt-PT', 'fa-IR', 'he-IL', 'ru-RU', 'ko-KR']
    const languages = ['English', 'Español', 'Nederlands', 'Português', 'فارسی', 'עִבְרִית', 'Русский', '한국어']

    const locale = locales[languages.indexOf(selectedLanguage)]
    localStorage.setItem("language", locale)
    i18n.locale = locale
}

export function getDefaultSettings() {
    return {
        version: import.meta.env.SAFETWITCH_TAG,
         audioOnly: {
             name: 'audioOnly',
             selected: false,
             type: 'checkbox'
         },
        defaultQuality: {
            name: 'defaultQuality',
            options: ['160p', '360p', '480p', '720p', '1080p'],
            selected: '480p',
            type: 'option'
        },
        language: {
            name: 'language',
            options: ['English', 'Español', 'Nederlands', 'Português', 'فارسی', 'עִבְרִית', 'Русский', '한국어'],
            selected: 'English',
            type: 'option'
        },
        chatVisible: {
            name: 'chatVisible',
            selected: false,
            type: 'checkbox'
        },
        streamTagsVisible: {
            name: 'streamTagsVisible',
            selected: true,
            type: 'checkbox'
        },
        streamerAboutSectionVisible: {
            name: 'streamerAboutSectionVisible',
            selected: true,
            type: 'checkbox'
        },
        autoplay: {
            name: 'autoplay',
            selected: false,
            type: 'checkbox'
        }
    }
}

export function syncUserSettings() {
    const defaultSettings = getDefaultSettings()
    let userSettings = localStorage.getItem('settings')
    if (!userSettings) return
    const parsedUserSettings = JSON.parse(userSettings)

    if(parsedUserSettings.version === import.meta.env.SAFETWITCH_TAG) {
        console.log('Settings up to date!')
        return
    } else {
        console.log('Settings outdated... Migrating')
    }


    const synced = {...defaultSettings, ...parsedUserSettings}
    synced.version = import.meta.env.SAFETWITCH_TAG
    localStorage.setItem('settings', JSON.stringify(synced))
    console.log('Migrated!')
}

export function getSetting(key: string): boolean | string {
    const storage = localStorage.getItem('settings')
    let parsed
    if (!storage) {
        parsed = getDefaultSettings()
    } else {
        parsed = JSON.parse(storage)
    }

    return parsed[key].selected
}

export function chatVisible() {
    const p = getSetting('chatVisible')
    // Flip becuase on the setting page it's
    // displayed as "Hide Chat", but the value
    // is chatVisible
    return !p
}
