<!-- component template -->
<template>
  <div data-name="manage_translation" class="page">

    <div class="navbar">
      <div class="navbar-inner">

        <div class="left">
          <button @click="backToMenu" class="button col align-items-center"><i class="fas fa-chevron-left"></i>
            {{ $root.appdict.btn_cancel }}</button>
          </a>
        </div>

        <div class="title manage-translation_title">{{ $root.appdict.lang_title }}</div>

        <div class="right">
          <button @click="saveChanges" class="button col align-items-center"><i class="fas fa-check-circle"></i>
            {{ $root.appdict.btn_save }}</button>
        </div>

      </div>
    </div>

    <div class="page-content">


      <div class="row pt2">
        <div class="col-100">
          <div class="block block-strong mt1">

            <div class="row align-items-center">
              <div class="col-60">
                <strong>{{ $root.appdict.lang_label_importexport }}</strong>
              </div>
              <button @click="importLanguage" class="col-20 button button-fill">{{ $root.appdict.btn_import }}</button>
              <button @click="exportLanguage" class="col-20 button button-fill">{{ $root.appdict.btn_export }}</button>
            </div>


          </div>
        </div>
      </div>

      <div class="row pb3">
        <div class="col-100">
          <div class="block-title">{{ $root.appdict.lang_info_title }}</div>
          <div class="block">
            {{ $root.appdict.lang_info_content }}
          </div>
        </div>
      </div>

      <div class="toolbar tabbar toolbar-bottom">
        <div class="toolbar-inner">
          <a href="#tab-1" class="tab-link tab-link-active"><strong>{{ $root.appdict.lang_label_teachertab }}</strong></a>
          <a href="#tab-2" class="tab-link"><strong>{{ $root.appdict.lang_label_studenttab }}</strong></a>
        </div>
      </div>
      <!-- Tabs -->
      <div class="tabs">

        <!-- First tab, active -->
        <div class="tab tab-active" id="tab-1">
          <div id="appdict-entry-root">


          </div>
        </div>
        <!-- Second tab -->
        <div class="tab" id="tab-2">
          <div id="gamedict-entry-root">


          </div>
        </div>

      </div>


    </div>

  </div>
</template>


<style>
</style>


<script>
  return {
    data: function () {
      return {

      }
    },
    methods: {
      backToMenu: function () {
        framework.dialog.confirm(framework.data.appdict.label_backtomenu, function () {
          mainView.router.back()
        })
      },
      saveChanges: function () {

        ipcRenderer.send('ipcF2M_saveLanguage', ui.manageLanguage.fn_returnDict())

        framework.dialog.confirm(framework.data.appdict.lang_confirm_save, function () {
          ipcRenderer.send('ipcF2M_relaunchApp')
        })

      },
      importLanguage: function () {

        let filepath = dialog.showOpenDialog({
          properties: ['openFile'],
          filters: [{ name: 'Curio Translation', extensions: ['curiotranslation'] }]
        })

        if (filepath !== undefined) {
          fs.readFile(filepath[0], 'utf8', function (err, data) {
            if (err) return console.log(err)

            ui.manageLanguage.fn_refreshDict(JSON.parse(data))

          })
        }

      },
      exportLanguage: function () {

        let filepath = dialog.showSaveDialog({
          filters: [{ name: 'Curio Translation', extensions: ['curiotranslation'] }]
        })

        if (filepath !== undefined) {
          ipcRenderer.send('ipcF2M_exportLanguage', {
            path: filepath,
            data: ui.manageLanguage.fn_returnDict()
          })

        }
      }

    },
    on: {
      pageBeforeIn: function () {

        ui.manageLanguage.fn_returnDict = function () {

          const studentEntrySelector = $$('.appdict-inputs')

          let appdictValues = {}
          $('.appdict-inputs').each(function () {
            let value = $(this).val()
            const key = $(this).data('key')

            if (value.trim() === "") {
              value = $(this).data('default')
            }

            appdictValues[key] = value
          })

          let gamedictValues = {}
          $('.gamedict-inputs').each(function () {
            let value = $(this).val()
            const key = $(this).data('key')

            if (value.trim() === "") {
              value = $(this).data('default')
            }

            gamedictValues[key] = value
          })

          return { app: appdictValues, game: gamedictValues }
        }


        ui.manageLanguage.fn_refreshDict = function (importDict) {

          let sourceApp = framework.data.appdict
          let sourceGame = framework.data.gamedict
          if (importDict !== undefined) {
            sourceApp = importDict.app
            sourceGame = importDict.game
          }

          $('#appdict-entry-root').empty()
          $('#gamedict-entry-root').empty()

          const catLabel = {
            btn: framework.data.appdict.lang_cat_btn,
            label: framework.data.appdict.lang_cat_label,
            home: framework.data.appdict.lang_cat_home,
            class: framework.data.appdict.lang_cat_class,
            scen: framework.data.appdict.lang_cat_scen,
            game: framework.data.appdict.lang_cat_game,
            endgame: framework.data.appdict.lang_cat_endgame,
            lang: framework.data.appdict.lang_cat_lang
          }

          const catOrder = ['btn', 'label', 'home', 'class', 'scen', 'game', 'endgame', 'lang']

          for (let catIndex = 0; catIndex < catOrder.length; catIndex++) {
            const catGroup = catOrder[catIndex]

            let catBlock = [
              `<div class="block-title">${catLabel[catGroup]}</div>
              <div class="block block-strong lang-block">`
            ]

            Object.entries(defaultDict.app).forEach(([key, value]) => {
              if (key.startsWith(catGroup)) {

                catBlock.push([
                  `<div class="row">
                  <div class="col-5"></div>
                  <div class="col-40 tr ws-normal align-self-center default-text">
                    ${value}
                  </div>
                  <div class="col-5 align-self-center">
                    <i class="fas fa-arrow-right"></i>
                  </div>
                  <div class="col-45 align-self-stretch current-text">
                    <textarea class="lang-input w-100 h-100 ba br1 bg-white b--light-silver appdict-inputs" data-key="${key}" data-default="${value}">${sourceApp[key]}</textarea>
                  </div>
                  <div class="col-5"></div>
                </div>`
                ])
              }
            })

            catBlock.push(["</div></div>"])
            $$('#appdict-entry-root').append(catBlock.join(""))


          }


          let gameBlock = [
            `<div class="block-title">${framework.data.appdict.lang_cat_gamelabels}</div>
            <div class="block block-strong lang-block">`
          ]


          let wildCardInfo = {
            phase3_c1: framework.data.appdict.lang_tooltip_subtopictitle,
            phase5_c1: framework.data.appdict.lang_tooltip_subtopicanswer,
            phase5_c2: framework.data.appdict.lang_tooltip_subtopicanswer,
            wait_login1: framework.data.appdict.lang_tooltip_username,
            wait_login2: framework.data.appdict.lang_tooltip_username
          }

          Object.entries(defaultDict.game).forEach(([key, value]) => {

            let defaultValue = value

            if (key in wildCardInfo) {
              defaultValue = defaultValue.replace("{...}", `<a class="tooltip-${key}">{...}</a>`)
            }

            gameBlock.push([
              `<div class="row">
                <div class="col-5"></div>
                <div class="col-40 tr ws-normal align-self-center default-text">
                  ${defaultValue}
                </div>
                <div class="col-5 align-self-center tr">
                  <i class="fas fa-arrow-right"></i>
                </div>
                <div class="col-45 align-self-stretch current-text">
                  <textarea class="lang-input w-100 h-100 ba br1 bg-white b--light-silver gamedict-inputs" data-key="${key}" data-default="${value}">${sourceGame[key]}</textarea>
                </div>
                <div class="col-5"></div>
              </div>`
            ])

          })

          gameBlock.push(["</div></div>"])
          $$('#gamedict-entry-root').append(gameBlock.join(""))



          Object.entries(wildCardInfo).forEach(([key, value]) => {
            ui.manageLanguage[`tmp_tooltip_${key}`] = framework.tooltip.create({
              targetEl: `.tooltip-${key}`,
              text: `{...} ${wildCardInfo[key]}`
            })
          })

        }


        ui.manageLanguage.fn_refreshDict()

      },
      pageAfterIn: function () {


      },
    }
  }
</script>