<!-- component template -->
<template>
  <div data-name="manage_scenario" 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-scenario_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="list inline-labels inset">
        <ul>
          <li class="item-content item-input">
            <div class="item-inner">
              <div class="item-title item-label">{{ $root.appdict.scen_label_topic }}</div>
              <div class="item-input-wrap">
                <input id="manage-scenario_input-topictitle" type="text"
                  placeholder="{{ $root.appdict.scen_label_topic_ph }}">
                <span class="input-clear-button"></span>
              </div>
            </div>
          </li>
        </ul>
      </div>

      <div class="edit_message dn">
        <hr>
        <div class="block">
          <div class="row align-items-center">
            <div class="col-75">
              <em>{{ $root.appdict.scen_edit_info }}</em>
            </div>

            <div class="col-5"></div>

            <div class="col-20">
              <button @click="removeScenario" class="button button-outline col align-items-center color-red"><i
                  class="fas fa-trash-alt pr2"></i>
                {{ $root.appdict.btn_delete }}</button>
            </div>
          </div>
        </div>
        <hr>
      </div>

      <div id="manage-scenario_subtopic-list">
      </div>

      <div class="block">
        <div class="row">
          <div class="col-30">

          </div>
          <div class="col-50"></div>

          <div class="col-20">
            <button @click="addNewSubtopic" id="scenario-create_btn-add-subtopic"
              class="col button button-small button-raised button-fill">{{ $root.appdict.scen_addtopic }}</button>
          </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 () {
        const initWith = ui.manageScenario.initWith
        const topicSelector = $$('#manage-scenario_input-topictitle')

        if (util.isEmpty(topicSelector.val())) {
          ui.manageScenario.fn_highlightError(topicSelector, framework.data.appdict.scen_error_emptytopic)
          return
        }

        const labelExist = ipcRenderer.sendSync('ipcSyncF2M_scenarioExists', topicSelector.val())
        const editingCurrent = initWith.mode == 'edit' ? initWith.data.label == topicSelector.val() : false

        if (labelExist && !editingCurrent) {
          ui.manageScenario.fn_highlightError(topicSelector, framework.data.appdict.scen_error_nameinuse)
          return
        }


        // For each sub topic -- check
        const subtopicsSelector = $$('.manage-scenario_subtopic-root')

        let subArr = []
        for (let i = 0; i < subtopicsSelector.length; i++) {
          const element = subtopicsSelector[i]
          const subtopicTitleSelector = $$(element).find('.subtopic-title')
          const subtopicQuestionSelector = $$(element).find('.subtopic-question')
          const subtopicCorrectSelector = $$(element).find('.subtopic-correctanswer')

          if (util.isEmpty(subtopicTitleSelector.val())) {
            ui.manageScenario.fn_highlightError(subtopicTitleSelector, framework.data.appdict.scen_error_emptytitle)
            return
          }

          if (util.isEmpty(subtopicQuestionSelector.val())) {
            ui.manageScenario.fn_highlightError(subtopicQuestionSelector, framework.data.appdict.scen_error_emptyquestion)
            return
          }

          if (util.isEmpty(subtopicCorrectSelector.val())) {
            ui.manageScenario.fn_highlightError(subtopicCorrectSelector, framework.data.appdict.scen_error_emptycorrect)
            return
          }

          const wrongAnswersSelector = $$(element).find('.subtopic-wronganswer')

          let wrongAnswers = []
          $$(wrongAnswersSelector).each(function (j) {
            const answer = $$(wrongAnswersSelector[j]).val()

            if (util.isEmpty(answer) == false) {
              wrongAnswers.push(answer)
            }

          })

          if (wrongAnswers.length < 1) {
            ui.manageScenario.fn_highlightError(wrongAnswersSelector, framework.data.appdict.scen_error_minanswer)
            return
          }

          // If all is okay, we add to the subarr
          let subtopicOutput = {
            subtopic: subtopicTitleSelector.val(),
            question: subtopicQuestionSelector.val(),
            correct: subtopicCorrectSelector.val(),
            wrong: wrongAnswers
          }
          subArr.push(subtopicOutput)
        }

        const saveOutput = {
          label: topicSelector.val(),
          subtopics: subArr
        }


        ipcRenderer.send('ipcF2M_addEditScenario', {
          mode: initWith.mode,
          data: saveOutput,
          id: initWith.mode == 'edit' ? initWith.data._id : ''
        })
        mainView.router.back()

      },
      addNewSubtopic: function () {
        const subTopicCount = $$(".manage-scenario_subtopic-root").length

        let vars = {
              number: subTopicCount + 1,
              title: "",
              question: "",
              correct: "",
              appdict: framework.data.appdict
            }

        const compiledHTML = ui.tmp.manageScenario_subtopic(vars)
        const addedSubTopic = $$("#manage-scenario_subtopic-list").append(compiledHTML)

        ui.manageScenario.fn_checkAmount()

      },
      removeScenario: function () {
        const initWith = ui.manageScenario.initWith

        framework.dialog.confirm(framework.data.appdict.scen_confirm_remove, function () {

          ipcRenderer.send('ipcF2M_addEditScenario', { mode: 'remove', id: initWith.data._id })
          mainView.router.back()
        })
      }
    },
    on: {
      pageBeforeIn: function () {

        ui.manageScenario.fn_checkAmount = () => {
          const subTopicCount = $$(".manage-scenario_subtopic-root").length

          if (subTopicCount >= 10) {
            $$("#scenario-create_btn-add-subtopic").addClass("disabled")
          } else {
            $$("#scenario-create_btn-add-subtopic").removeClass("disabled")
          }

          // Re-register click event
          $('.btn-remove-subtopic').on('click', function () {

            const subTopicCount = $$(".manage-scenario_subtopic-root").length
            if (subTopicCount <= 1) {
              const toastTop = framework.toast.create({
                text: framework.data.appdict.scen_error_mintopic,
                position: 'top',
                closeTimeout: 4000,
                destroyOnClose: true
              })
              toastTop.open()
              return
            }

            $(this).addClass('disabled')
            $(this).closest('.manage-scenario_subtopic-root').css('overflow', 'hidden')
            $(this).closest('.manage-scenario_subtopic-root').animate({ opacity: 0, height: 0 }, {
              duration: 300, complete: function () {
                $(this).remove()
                $('span.subtopic-number').each(function (index) {
                  $(this).html(index + 1)
                })
                ui.manageScenario.fn_checkAmount()
              }
            })
          })

        }

        ui.manageScenario.fn_highlightError = (selector, errorText) => {
          const dom = selector[0]
          dom.scrollIntoView({
            block: 'center',
            behavior: 'smooth'
          })

          const toastTop = framework.toast.create({
            text: errorText,
            position: 'top',
            closeTimeout: 4000,
            destroyOnClose: true
          })
          toastTop.open()

          $(selector).closest('li.item-content').addClass('highlightIssue highlightActive')
          $(selector).change(function () {
            $(this).closest('li.item-content').removeClass('highlightActive')
          })
        }


        const initWith = ui.manageScenario.initWith

        if (initWith.mode == 'create') {

          $('.manage-scenario_title').html(framework.data.appdict.scen_title_create)
          const compiledHTML = ui.tmp.manageScenario_subtopic({ number: 1, appdict: framework.data.appdict })
          $("#manage-scenario_subtopic-list").append(compiledHTML)

        } else if (initWith.mode == 'edit') {

          $('.edit_message').removeClass('dn')
          $('.manage-scenario_title').html(framework.data.appdict.scen_title_edit)
          $('#manage-scenario_input-topictitle').val(initWith.data.label).trigger('change')

          initWith.data.subtopics.forEach((sub, index) => {
            let vars = {
              number: index + 1,
              title: sub.subtopic,
              question: sub.question,
              correct: sub.correct,
              appdict: framework.data.appdict
            }

            if (sub.wrong != undefined) {
              sub.wrong.forEach((wrong, index) => {
                vars[`wrong_${index + 1}`] = wrong
              })
            }


            const compiledHTML = ui.tmp.manageScenario_subtopic(vars)
            $("#manage-scenario_subtopic-list").append(compiledHTML)

          })

        }


        ui.manageScenario.fn_checkAmount()

      },
      pageAfterIn: function () {

      },
    }
  }
</script>