'use strict'

angular.module('EXAM').controller('Exam', ['$scope', '$http', '$mdDialog', 'EXAMSERVICES', 'SwapLang', function($scope, $http, $mdDialog, EXAMSERVICES, SwapLang){
  let cscForm = document.cscform
  $scope.timeselected = {
    hour: [],
    minute: []
  }

  for (let i=0; i<=24; i++){
    $scope.timeselected.hour.push(i)
  }

  for (let i=0; i<=59; i++){
    $scope.timeselected.minute.push(i)
  }


  $scope.tmpobj = ''
  $scope.mylang = 'eng'
  $scope.question = new Question()
  $scope.examid = $('input[name="__examid"]').val()
  $scope.exam = {
    examdata: {
      topic: {
        tha: '',
        eng: ''
      },
      description: {
        tha: '',
        eng: ''
      },
      timelimit: {
        istimelimit: false,
        hour: 0,
        minute: 0
      },
      evaluate: {
        isevaluate: false,
        passing: '', // score passing
        totalscore: ''
      },
      showscore: false,
      age: '',
      autochecking: false

    },
    question: $scope.question.getQuestion()
  }
  $scope.mdtoolbar = {
    isopen: false,
    mode: 'md-scale'
  }


  $scope.initLang = function(p_lang){
    $scope.mylang = p_lang
  }

  // NOTE: Initialize function
  $scope.checkSomething = function(){
    console.log($scope.exam)
  }

  $scope.checkScore = function(ansobj){
    if (ansobj.value === undefined || ansobj.value === null){
      ansobj.value = ''
    }
  }
  $scope.calTypeOne = function(ansobj){
    let score = 0
    if (ansobj.value != '' && ansobj.value != null){
      score = parseInt(ansobj.value)
    }
    return score
  }

  $scope.calTypeTwo = function(ansobj){
    let score = Math.max.apply(null, ansobj.choice.map(ans => ans.value))
    return score
  }

  $scope.calTypeThree = function(ansobj){
    let score = Math.max.apply(null, ansobj.map(ans => ans.value))
    return score
  }

  $scope.calScore = function(qsubobj){
    let score = 0
    qsubobj.forEach((q) => {
      if (q.type != 2 && q.type != 8){
        score += $scope.calTypeOne(q.ansgroup)
      } else if (q.type === 2){
        score += $scope.calTypeTwo(q.ansgroup)
      } else if (q.type === 8){
        score += $scope.calScore(q.ansgroup)
      }
    })
    return score
  }

  $scope.previewExam = function(){
    let mapform = document.createElement('form')
    mapform.target = 'Map'
    mapform.method = 'POST'
    mapform.action = 'previewexam.jsp'

    let mapinput = document.createElement('input')
    mapinput.type = 'hidden'
    mapinput.name = '__exam'
    mapinput.value = JSON.stringify($scope.exam)
    mapform.appendChild(mapinput)

    document.body.appendChild(mapform)

    var win = window.open('', 'Map', 'left=150,top=150,width=2000,height=2000,toolbar=no,status=yes,scrollbars=yes,resizable=yes')
    if (win){
      mapform.submit()
      win.focus()
    }
  }


  $scope.checkAutoMode = function(){
    return new Promise((resolve, reject) => {
      let result = false
      let chklv1 = [], chklv2 = [], chklv3 = [] , listlv2 = [], listlv3 = []

      chklv1 = $scope.exam.question.filter((obj) => { return obj.type === 1})
      listlv2 = $scope.exam.question.filter((obj) => {return obj.type === 8})

      if (listlv2.length > 0){
        listlv2.forEach((lv2obj) => {
          chklv2 = lv2obj.ansgroup.filter((obj) => {return obj.type === 1})
          listlv3 = lv2obj.ansgroup.filter((obj) => {return obj.type === 8})

          if (listlv3.length > 0){
            listlv3.forEach((lv3obj) => {
              chklv3 = lv3obj.ansgroup.filter((obj) => {return obj.type === 1})
            })
          }
        })
      }

      if (chklv1.length === 0 && chklv2.length === 0 && chklv3.length === 0 ){
        result = true
      }
      resolve(result)
    })
  }


  $scope.save = function(){
    let allobj = {
      examid: $scope.examid,
      examdata: $scope.exam.examdata,
      question: $scope.exam.question
    }

    $scope.checkAutoMode().then((result) => {
      $scope.exam.examdata.autochecking = result
    }).then(() => {
      SwapLang.getConfirm(1).then(function () {
        EXAMSERVICES.ManageExam.save({exam: allobj}).$promise.then(()=> {
          SwapLang.getAlert(18).then(function () {
            $scope.examid = result.examid
          })
        }, (error)=>{
          SwapLang.getAlert(17, error.data.result)
        })
      })
      // let con = confirm(MyCode[1])
      // if (con){
      //   EXAMSERVICES.ManageExam.save({exam: allobj}).$promise.then(function(result){
      //     $scope.examid = result.examid
      //     alert(MyCode[18])
      //   })
      // }
    })
  }

  $scope.delete = function() {
    SwapLang.getConfirm(4).then(function () {
      EXAMSERVICES.ManageExam.delete({examid: $scope.examid}).$promise.then(()=> {
        SwapLang.getAlert(19).then(function () {
          cscForm.action = "EXAM_LIST.jsp"
          cscForm.submit()
        })
      }, (error)=>{
        SwapLang.getAlert(7, error.data.result)
      })
    })
  }

  $scope.setCalScore = function(){
    $scope.exam.examdata.evaluate.calTotalScore = function(){
      let score = 0
      let qobj = $scope.question.getQuestion()
      score += parseInt($scope.calScore(qobj))
      return score
    }
  }

  if ($scope.examid != 0){
    EXAMSERVICES.ManageExam.query({examid: $scope.examid}).$promise.then(function(result){
      $scope.exam = result.exam
      $scope.question.setQuestion(result.exam.question)
      $scope.setCalScore()
    })
  } else {
    $scope.setCalScore()
  }

  $scope.setExamId = function(){
    console.log('hi')
  }
}])
.directive('question', function(){
  return {
    restrict: 'E',
    scope: {
      obj: '=obj',
      level: '=level',
      pindex: '=pindex',
      gpindex: '=gpindex'
    },
    controller: 'Question',
    templateUrl: 'question.html'
  }
})
// NOTE: type = 1 -> textbox [อัตนัย]
// NOTE: type = 2 -> single choice [ปรนัย] -> มีคะแนนข้อเดียว / มีคะแนนทุกข้อแต่ไม่เท่ากัน
// NOTE: type = 3 -> Multi choice -> มีคะแนนข้อเดียว / มีคะแนนทุกข้อแต่ไม่เท่ากัน
// NOTE: type = 4 -> Sort Sentence -> เรียงประโยค
// NOTE: type = 5 -> Pairs text -> จับคู่ข้อความ
// NOTE: type = 6 -> Pairs picture -> จับคู่รูปภาพ
// NOTE: type = 7 -> Pairs Picture/text -> จับคู่รูปภาพกับข้อความ
// NOTE: type = 8 -> Sub question