import { englishPage } from "./language"

async function handleRequest(request) {
    const url = new URL(request.url)
    let language
    if (url.searchParams.get("base") == "ip") {
      // The language to be displayed will be determined based on the IP address
      language = clientLanguageBaseIp(request)
    } else {
      // The language to be displayed will be determined based on the browser's language settings
      language = clientLanguageBaseBrowserSetting(request)
    }
    const countryStrings = (englishPage(request) ? strings_en[language] : strings[language]) || {}
    const response = await fetch(request.url)

    return new HTMLRewriter()
        .on('[data-i18n-key]', new ElementHandler(countryStrings))
        .transform(response)
}

function clientLanguageBaseIp(request) {
    const code = request.ws.countryCode
    if (code == "CN" || code == "TW" || code == "HK") {
      return "zh"
    } else if (code == "DE") {
      return "de"
    } else if (code == "JP") {
      return "ja"
    } else {
      return "en"
    }
}

function clientLanguageBaseBrowserSetting(request) {
    // Accept-Language: zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7
    try {
        const languageHeader = request.headers.get('Accept-Language')
        return languageHeader.split(';')[0].split(',')[0].split('-')[0]
    } catch (e) {
        return 'zh'
    }
}

class ElementHandler {
    constructor(countryStrings) {
      this.countryStrings = countryStrings
    }
  
    element(element) {
      const i18nKey = element.getAttribute('data-i18n-key')
      if (i18nKey) {
        const translation = this.countryStrings[i18nKey]
        if (translation) {
          element.setInnerContent(translation)
        }
      }
    }
  }

  

  const strings_en = {
    de: {
      title: 'Beispielseite',
      headline: 'Beispielseite',
      subtitle:
        'Dies ist meine Beispielseite. Abhängig davon, wo auf der Welt Sie diese Site besuchen, wird dieser Text in die entsprechende Sprache übersetzt.',
      disclaimer:
        'Haftungsausschluss: Die anfänglichen Übersetzungen stammen von Google Translate, daher sind sie möglicherweise nicht perfekt!',
      tutorial:
        'Das Tutorial für dieses Projekt finden Sie in der CDNetworks ECA-Dokumentation.',
      copyright: 'Design von HTML5 UP.',
    },
    ja: {
      title: 'サンプルサイト',
      headline: 'サンプルサイト',
      subtitle:
        'これは私の例のサイトです。 このサイトにアクセスする世界の場所に応じて、このテキストは対応する言語に翻訳されます。',
      disclaimer:
        '免責事項:最初の翻訳はGoogle翻訳からのものですので、完璧ではないかもしれません!',
      tutorial:
        'CDNetworks ECAのドキュメントでこのプロジェクトのチュートリアルを見つけてください。',
      copyright: 'HTML5 UPによる設計。',
    },
    zh: {
        title: '示例站点',
        headline: '示例站点',
        subtitle:
          '这是我的示例站点。根据您访问本网站的地点,本文将被翻译成相应的语言。',
        disclaimer:
          '免责声明:最初的翻译来自谷歌翻译,所以他们可能不完美!',
        tutorial:
          '在CDNetworks ECA文档中找到这个项目的教程。',
        copyright: '由HTML5 UP设计。',
      },
    en: {
        title: 'Example Site',
        headline: 'Example Site',
        subtitle:
          'THIS IS MY EXAMPLE SITE. DEPENDING ON WHERE IN THE WORLD YOU VISIT THIS SITE, THIS TEXT WILL BE TRANSLATED TO THE CORRESPONDING LANGUAGE.',
        disclaimer:
          'DISCLAIMER: THE INITIAL TRANSLATIONS ARE FROM GOOGLE TRANSLATE, SO THEY MAY NOT BE PERFECT!',
        tutorial:
          'FIND THE TUTORIAL FOR THIS PROJECT IN THE CDNetworks ECA DOCUMENTATION.',
        copyright: 'DESIGN BY HTML5 UP.',
      }
  }
                    
addEventListener("fetch", event => {
    return event.respondWith(handleRequest(event.request))
})