<!-- component template -->
<template>
  <div data-name="manage_class" 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-class_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.class_label }}</div>
              <div class="item-input-wrap">
                <input id="manage-class_input-topictitle" type="text" placeholder="{{ $root.appdict.class_label_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.class_edit_info }}</em>
            </div>

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

            <div class="col-20">
              <button @click="removeClass" 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 class="data-table card mh3">
        <table>
          <thead>
            <tr>
              <th class="w-50"><strong>{{ $root.appdict.class_name_label }}</strong></th>
              <th><strong>{{ $root.appdict.class_team_label }}</strong></th>
              <th class="w-20"></th>
              <th class="w-10"></th>
            </tr>
          </thead>
          <tbody id="manage-class_student-list">


          </tbody>
        </table>
      </div>



      <div class="block mt1 pl4">
        <div class="row">
          <div class="col-80"><em>{{ $root.appdict.class_studentcount }} <span
                class="manage-class_student-count"></span></em></div>

          <div class="col-20">
            <button @click="addNewStudent" id="manage-claass_btn-add-student"
              class="col button button-small button-raised button-fill">{{ $root.appdict.class_addstudent }}</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 () {
        // console.log(ui.manageClass.tmp_student)
        const initWith = ui.manageClass.initWith
        const classnameSelector = $$('#manage-class_input-topictitle')

        if (util.isEmpty(classnameSelector.val())) {
          ui.manageClass.fn_highlightErrorDiv(classnameSelector, framework.data.appdict.class_error_emptyclass)
          return
        }


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

        if (labelExist && !editingCurrent) {
          ui.manageClass.fn_highlightErrorDiv(classnameSelector, framework.data.appdict.class_error_nameinuse)
          return
        }


        // For each sub topic -- check
        const studentEntrySelector = $$('.manage-class_student-entry')

        // check if all unique

        let studentList = []
        for (let i = 0; i < studentEntrySelector.length; i++) {
          const element = studentEntrySelector[i]
          const studentNameSelector = $$(element).find('.manage-class_input-username')
          const studentTeamSelector = $$(element).find('.manage-class_select-team')

          // Check if not empty
          if (util.isEmpty(studentNameSelector.val())) {
            ui.manageClass.fn_highlightErrorDiv($$(element), framework.data.appdict.class_error_emptystudent, true)
            return
          }

          // Check if has space character
          if ((studentNameSelector.val()).indexOf(' ') >= 0) {
            ui.manageClass.fn_highlightErrorDiv($$(element), framework.data.appdict.class_error_studentspaces, true)
            return
          }

          // Check if unique
          const existing = studentList.filter(student => student.username == studentNameSelector.val())

          if (existing.length > 0) {
            ui.manageClass.fn_highlightErrorDiv($$(element), framework.data.appdict.class_error_studentinuse, true)
            return
          } else {
            studentList.push(
              { username: studentNameSelector.val(), defaultteam: studentTeamSelector.val() }
            )
          }
        }

        const saveOutput = {
          label: classnameSelector.val(),
          students: studentList
        }


        ipcRenderer.send('ipcF2M_addEditClass', {
          mode: initWith.mode,
          data: saveOutput,
          id: initWith.mode == 'edit' ? initWith.data._id : ''
        })
        mainView.router.back()
      },
      addNewStudent: function () {
        $("#manage-class_student-list").append(ui.manageClass.tmp_student)
        ui.manageClass.fn_refreshEntries()

      },
      removeClass: function () {
        const initWith = ui.manageClass.initWith

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

          ipcRenderer.send('ipcF2M_addEditClass', { mode: 'remove', id: initWith.data._id })
          mainView.router.back()
        })
      }

    },
    on: {
      pageBeforeIn: function () {

        ui.manageClass.tmp_student = Template7.compile(
          `<tr class="manage-class_student-entry">
            <td class="pr3">
              <input class="w-100 manage-class_input-username" type="text" placeholder="${ framework.data.appdict.class_student_ph }" value={{ name }}>
            </td>
            <td>
              <div class="item-input-wrap input-dropdown-wrap">
                <select class="w-100 pointer manage-class_select-team">
                  <option {{#js_if "this.team === 'random' "}}selected="selected"{{/js_if}} value="random">${ framework.data.appdict.class_label_random }</option>
                  <option {{#js_if "this.team === '1' "}}selected="selected"{{/js_if}} value="1">${ framework.data.appdict.label_team } 1</option>
                  <option {{#js_if "this.team === '2' "}}selected="selected"{{/js_if}} value="2">${ framework.data.appdict.label_team } 2</option>
                  <option {{#js_if "this.team === '3' "}}selected="selected"{{/js_if}} value="3">${ framework.data.appdict.label_team } 3</option>
                </select>
              </div>
            </td>
            <td></td>
            <td>
              <button class="btn-remove-student col button button-small button-outline color-red">${ framework.data.appdict.class_btn_removestudent }</button>

            </td>
          </tr>`
        )

        ui.manageClass.fn_highlightErrorDiv = (selector, errorText, table = false) => {
          console.log(selector)
          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()

          if (table) {
            $(selector).addClass('highlightIssueTable highlightActiveTable')
            $(selector).find('input').change(function () {
              console.log(this)
              $(this).closest('tr').removeClass('highlightActiveTable')
            })
          } else {
            $(selector).closest('li.item-content').addClass('highlightIssue highlightActive')
            $(selector).change(function () {
              $(this).closest('li.item-content').removeClass('highlightActive')
            })
          }

        }

        ui.manageClass.fn_refreshEntries = () => {
          const subTopicCount = $$(".manage-class_student-entry").length
          $('.manage-class_student-count').html(subTopicCount)

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

            const studentCount = $$(".manage-class_student-entry").length
            if (studentCount <= 3) {
              const toastTop = framework.toast.create({
                text: framework.data.appdict.class_error_mincount,
                position: 'top',
                closeTimeout: 4000,
                destroyOnClose: true
              })
              toastTop.open()
              return
            }

            $(this).addClass('disabled')
            $(this).closest('.manage-class_student-entry').animate({ opacity: 0 }, {
              duration: 300, complete: function () {
                $(this).remove()
                ui.manageClass.fn_refreshEntries()
              }
            })
          })

        }



        const initWith = ui.manageClass.initWith

        if (initWith.mode == 'create') {
          $('.manage-class_title').html(framework.data.appdict.class_edit_title)

          $("#manage-class_student-list").append(ui.manageClass.tmp_student)
          $("#manage-class_student-list").append(ui.manageClass.tmp_student)
          $("#manage-class_student-list").append(ui.manageClass.tmp_student)

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

          // for each, search the correct option and select it by adding 'selected' attribute
          $('.edit_message').removeClass('dn')
          $('.manage-class_title').html(framework.data.appdict.class_title_edit)
          $('#manage-class_input-topictitle').val(initWith.data.label).trigger('change')


          initWith.data.students.forEach((entry, index) => {
            let vars = {
              name: entry.username,
              team: entry.defaultteam
            }
            $("#manage-class_student-list").append(ui.manageClass.tmp_student(vars))

          })



        }

        ui.manageClass.fn_refreshEntries()
      },
      pageAfterIn: function () {

      },
    }
  }
</script>