'use strict'

angular.module('myHR').controller('PreviewExam', ['$scope', '$http', '$mdDialog', 'router', 'SwapLang', function($scope, $http, $mdDialog, router, SwapLang){
  $scope.examdata = router.examdata
  $scope.question = new Question()
  $scope.question.setQuestion(router.question)
  $scope.swlang = SwapLang
  $scope.fabtool = {
    isopen: false,
    classname: 'md-fling',
    list: []
  }
  //<editor-fold desc="For DHAS">
    //<editor-fold desc="EXAM NO.7 ADVANCE ENGLISH LANGUAGE">
    $scope.isDHASAdvanceEnglish = $scope.examdata.topic.tha === "ADVANCE ENGLISH LANGUAGE" ||
      $scope.examdata.topic.eng === "ADVANCE ENGLISH LANGUAGE"
    /*
     76+     A+
     73-75   A
     71-72   A-
     69-70   B+
     67-68   B
     66      B-
     64-65   C+
     62-63   C
     61      C-
     60      D+
     58-59   D
     57      D-
     56-     F
     */
    if ($scope.isDHASAdvanceEnglish) {
      $scope.ABAC = 'N/A'
      $scope.UTCC = 'N/A'
      let score = Math.ceil($scope.question.getRealScore($scope.question.getQuestion()))
      let totalScore = (score) ? score : 0
      switch (true) {
        case (totalScore >= 0 && totalScore <= 44):
          $scope.ABAC = 'F'
          $scope.UTCC = 'F'
          break;
        case (totalScore >= 45 && totalScore <= 46):
          $scope.ABAC = 'F'
          $scope.UTCC = 'D-'
          break;
        case (totalScore >= 47 && totalScore <= 48):
          $scope.ABAC = 'F'
          $scope.UTCC = 'D'
          break;
        case (totalScore === 49):
          $scope.ABAC = 'F'
          $scope.UTCC = 'D'
          break;
        case (totalScore >= 50 && totalScore <= 51):
          $scope.ABAC = 'F'
          $scope.UTCC = 'C-'
          break;
        case (totalScore >= 52 && totalScore <= 54):
          $scope.ABAC = 'F'
          $scope.UTCC = 'C'
          break;
        case (totalScore >= 55 && totalScore <= 56):
          $scope.ABAC = 'F'
          $scope.UTCC = 'C+'
          break;
        case (totalScore === 57):
          $scope.ABAC = 'D-'
          $scope.UTCC = 'B-'
          break;
        case (totalScore === 58):
          $scope.ABAC = 'D'
          $scope.UTCC = 'B-'
          break;
        case (totalScore === 59):
          $scope.ABAC = 'D'
          $scope.UTCC = 'B'
          break;
        case (totalScore === 60):
          $scope.ABAC = 'D+'
          $scope.UTCC = 'B'
          break;
        case (totalScore === 61):
          $scope.ABAC = 'C-'
          $scope.UTCC = 'B+'
          break;
        case (totalScore >= 62 && totalScore <= 63):
          $scope.ABAC = 'C'
          $scope.UTCC = 'A-'
          break;
        case (totalScore >= 64 && totalScore <= 65):
          $scope.ABAC = 'C+'
          $scope.UTCC = 'A'
          break;
        case (totalScore === 66):
          $scope.ABAC = 'B-'
          $scope.UTCC = 'A'
          break;
        case (totalScore >= 67 && totalScore <= 68):
          $scope.ABAC = 'B'
          $scope.UTCC = 'A+'
          break;
        case (totalScore >= 69 && totalScore <= 70):
          $scope.ABAC = 'B+'
          $scope.UTCC = 'A+'
          break;
        case (totalScore >= 71 && totalScore <= 72):
          $scope.ABAC = 'A-'
          $scope.UTCC = 'A+'
          break;
        case (totalScore >= 73 && totalScore <= 75):
          $scope.ABAC = 'A'
          $scope.UTCC = 'A+'
          break;
        case (totalScore >= 76):
          $scope.ABAC = 'A+'
          $scope.UTCC = 'A+'
          break;
      }
    }
    //</editor-fold>
    //<editor-fold desc="ข้อสอบที่ 3 ความถนัดเชิงเหตุผลนามธรรม (ABSTRACT REASONING APTITUDE TEST)">
    $scope.isDHASAbstractReasoning = $scope.examdata.topic.tha === "ความถนัดเชิงเหตุผลนามธรรม (ABSTRACT REASONING APTITUDE TEST)" ||
      $scope.examdata.topic.eng === "ความถนัดเชิงเหตุผลนามธรรม (ABSTRACT REASONING APTITUDE TEST)"

    if ($scope.isDHASAbstractReasoning) {
      $scope.DHASAbstractReasoningGrade = 'Unknown'
      let score = $scope.question.getRealScore($scope.question.getQuestion())
      let totalScore = (score) ? score : 0
      switch (true) {
        case (totalScore >= 0 && totalScore <= 8):
          $scope.DHASAbstractReasoningGrade = 'F'
          break;
        case (totalScore === 9):
          $scope.DHASAbstractReasoningGrade = 'D-'
          break;
        case (totalScore === 10):
          $scope.DHASAbstractReasoningGrade = 'D'
          break;
        case (totalScore === 11):
          $scope.DHASAbstractReasoningGrade = 'D+'
          break;
        case (totalScore === 12):
          $scope.DHASAbstractReasoningGrade = 'C-'
          break;
        case (totalScore >= 13 && totalScore <= 14):
          $scope.DHASAbstractReasoningGrade = 'C'
          break;
        case (totalScore === 15):
          $scope.DHASAbstractReasoningGrade = 'C+'
          break;
        case (totalScore === 16):
          $scope.DHASAbstractReasoningGrade = 'B-'
          break;
        case (totalScore >= 17 && totalScore <= 18):
          $scope.DHASAbstractReasoningGrade = 'B'
          break;
        case (totalScore === 19):
          $scope.DHASAbstractReasoningGrade = 'B+'
          break;
        case (totalScore >= 20 && totalScore <= 21):
          $scope.DHASAbstractReasoningGrade = 'A-'
          break;
        case (totalScore >= 22 && totalScore <= 23):
          $scope.DHASAbstractReasoningGrade = 'A'
          break;
        case (totalScore >= 24):
          $scope.DHASAbstractReasoningGrade = 'A+'
          break;
      }
    }
    //</editor-fold>
    //<editor-fold desc="ข้อสอบที่ 1 แบบสำรวจบุคลิกภาพ Personality Inventory test">
    $scope.isDHASPIT = $scope.examdata.topic.tha === "แบบสำรวจบุคลิกภาพ Personality Inventory test" ||
      $scope.examdata.topic.eng === "แบบสำรวจบุคลิกภาพ Personality Inventory test"
    if($scope.isDHASPIT) {
      $scope.scoreDHASPIT = $scope.question.getDHASPIT(router)
    }
    //</editor-fold>
    //<editor-fold desc="ข้อสอบที่ 2 ความพร้อมหัวหน้างาน Supervisory Readiness test">
  $scope.isDHASSupReadTest = $scope.examdata.topic.tha.includes("ความพร้อมหัวหน้างาน") ||
    $scope.examdata.topic.eng.includes("ความพร้อมหัวหน้างาน")

  if ($scope.isDHASSupReadTest) {
    //Set 3
    let setThreeScore = 0
    $scope.question.question[2].ansgroup.forEach(($item) => {
      let sumSentence = 12
      $item.ansgroup.sentence.forEach(($sentence) => {
        let choiceScore = Math.abs($sentence.value - $sentence.answer) * -1
        sumSentence += choiceScore
      })
      setThreeScore += sumSentence
    })
    //Set 1 + 2
    let copyQuestion = JSON.parse(JSON.stringify($scope.question));
    copyQuestion.question.splice(2, 1)
    let setOneTwoScore = $scope.question.getRealScore(copyQuestion.question)
    

    $scope.DHASSupReadTestGrade = 'Unknown'
    $scope.DHASSupReadTestScore = setThreeScore + setOneTwoScore
    let totalScore = ($scope.DHASSupReadTestScore) ? $scope.DHASSupReadTestScore : 0
    switch (true) {
      case (totalScore >= 0 && totalScore <= 129):
        $scope.DHASSupReadTestGrade = 'F'
        break;
      case (totalScore >= 130 && totalScore <= 132):
        $scope.DHASSupReadTestGrade = 'D-'
        break;
      case (totalScore >= 133 && totalScore <= 134):
        $scope.DHASSupReadTestGrade = 'D'
        break;
      case (totalScore >= 135 && totalScore <= 136):
        $scope.DHASSupReadTestGrade = 'D+'
        break;
      case (totalScore >= 137 && totalScore <= 138):
        $scope.DHASSupReadTestGrade = 'C-'
        break;
      case (totalScore >= 139 && totalScore <= 140):
        $scope.DHASSupReadTestGrade = 'C'
        break;
      case (totalScore >= 141 && totalScore <= 144):
        $scope.DHASSupReadTestGrade = 'C+'
        break;
      case (totalScore >= 145 && totalScore <= 149):
        $scope.DHASSupReadTestGrade = 'B-'
        break;
      case (totalScore >= 150 && totalScore <= 154):
        $scope.DHASSupReadTestGrade = 'B'
        break;
      case (totalScore >= 155 && totalScore <= 159):
        $scope.DHASSupReadTestGrade = 'B+'
        break;
      case (totalScore >= 160 && totalScore <= 164):
        $scope.DHASSupReadTestGrade = 'A-'
        break;
      case (totalScore >= 165 && totalScore <= 169):
        $scope.DHASSupReadTestGrade = 'A'
        break;
      case (totalScore >= 170):
        $scope.DHASSupReadTestGrade = 'A+'
        break;
    }
  }
  
  
    //</editor-fold>

  //</editor-fold>

  //<editor-fold desc="For SENA">
    $scope.isSenaMentalHealth = $scope.examdata.topic.tha === "แบบประเมินความฉลาดทางอารมณ์ของกรมสุขภาพจิต" ||
        $scope.examdata.topic.eng === "แบบประเมินความฉลาดทางอารมณ์ของกรมสุขภาพจิต"
    /*
     1.1 0-5
     1.2 6-11
     1.3 12-17
     2.1 18-23
     2.2 24-29
     2.3 30-35
     3.1 36-39
     3.2 40-45
     3.3 46-51
     */
    if ($scope.isSenaMentalHealth) {
        let score = {
            "oneOne" : 0,
            "oneTwo" : 0,
            "oneThree" : 0,
            "twoOne" : 0,
            "twoTwo" : 0,
            "twoThree" : 0,
            "threeOne" : 0,
            "threeTwo" : 0,
            "threeThree" : 0,
        }
        angular.forEach($scope.question.question[0].ansgroup, function (value, key) {
            if (value.ansgroup.answer !== -1) {
                let itemScore = value.ansgroup.choice[value.ansgroup.answer].value
                let ansScore = (itemScore) ? itemScore : 0
                switch (true) {
                    case (key >= 0 && key <= 5):
                        score.oneOne += ansScore
                        break;
                    case (key >= 6 && key <= 11):
                        score.oneTwo += ansScore
                        break;
                    case (key >= 12 && key <= 17):
                        score.oneThree += ansScore
                        break;
                    case (key >= 18 && key <= 23):
                        score.twoOne += ansScore
                        break;
                    case (key >= 24 && key <= 29):
                        score.twoTwo += ansScore
                        break;
                    case (key >= 30 && key <= 35):
                        score.twoThree += ansScore
                        break;
                    case (key >= 36 && key <= 39):
                        score.threeOne += ansScore
                        break;
                    case (key >= 40 && key <= 45):
                        score.threeTwo += ansScore
                        break;
                    case (key >= 46 && key <= 51):
                        score.threeThree += ansScore
                        break;
                }
            }
        })
        $scope.labels = ["1.1 ควบคุมตนเอง", "1.2 เห็นใจผู้อื่น", "1.3 รับผิดชอบ", "2.1 มีแรงจูงใจ", "2.2 ตัดสินใจและแก้ไขปัญหา", "2.3 สัมพันธภาพ", "3.1 ภูมิใจตนเอง", "3.2 พอใจชีวิต", "3.3 สุขสงบทางใจ"];
        $scope.series = ['ต่ำสุด', 'สูงสุด', 'คะแนนที่ได้'];

        $scope.data = [
            [14, 16, 18, 16, 15, 15, 10, 16, 16],
            [18, 21, 23, 22, 21, 21, 14, 22, 21],
            [score.oneOne, score.oneTwo, score.oneThree, score.twoOne, score.twoTwo, score.twoThree, score.threeOne, score.threeTwo, score.threeThree]
        ];
        $scope.onClick = function (points, evt) {

        };
        $scope.datasetOverride = [{ yAxisID: 'y-axis-1' }];
        $scope.options = {
            scales: {
                yAxes: [
                    {
                        id: 'y-axis-1',
                        type: 'linear',
                        display: true,
                        position: 'left'
                    },
                ]
            }
        };
    }
  //</editor-fold>






  $scope.getFlagBtn = function(){
    let listbtn = []
    // if (router.status == 3 || $scope.examdata.autochecking === false){
    //   listbtn.push({
    //     name: 'passing',
    //     faicon: 'fa-check',
    //     classcolor: 'icon-passing',
    //     state: 1
    //   },{
    //     name: 'fail',
    //     faicon: 'fa-times',
    //     classcolor: 'icon-fail',
    //     state: -1
    //   })
    // }

    if ((router.status == 3) && ($scope.examdata.evaluate.isevaluate)){
      listbtn.push({
        name: 'passing',
        faicon: 'fa-check',
        classcolor: 'icon-passing',
        state: 1
      },{
        name: 'fail',
        faicon: 'fa-times',
        classcolor: 'icon-fail',
        state: -1
      })
    }

    if (router.status == -10){
      listbtn.push({
        name: 'approve',
        faicon: 'fa-check',
        classcolor: 'icon-approve',
        state: 10
      })
    }

    if (router.status != 2 && router.status != 1){
      listbtn.push({
        name: 'skip',
        faicon: 'fa-forward',
        classcolor: 'md-raised',
        state: 2
      })
    }

    return listbtn
  }


  $scope.checkSummaryPassing = function(){
    let classname = ''
    if ($scope.examdata.evaluate.isevaluate){
      if ($scope.question.getRealScore($scope.question.getQuestion()) >= $scope.examdata.evaluate.passing){
        classname = 'summary-passing'
      } else {
        classname = 'summary-fail'
      }
    }
    return classname
  }

  $scope.checkEvaluateStatus = function(){
    let classname = 'summary-fail'
    if ($scope.examdata.evaluate.isevaluate){
      classname = 'summary-passing'
    }

    return classname
  }

  $scope.submitToPass = function(){
    let obj = {
      state: 1
    }
    $mdDialog.hide(obj)
  }

  $scope.submitToFail = function(){
    let obj = {
      state: -1
    }

    $mdDialog.hide(obj)
  }

  $scope.skip = function(){
    let obj = {
      state: 2
    }

    $mdDialog.hide(obj)
  }

  $scope.close = function(){
    $mdDialog.cancel()
  }

  $scope.submitBtn = function(state){
    $mdDialog.hide({state: state})
  }

  // NOTE: auto process here
  $scope.fabtool.list = $scope.getFlagBtn()
}])
.directive('previewQuestion', function(){
  return {
    restrict: 'E',
    scope: {
      obj: '=obj',
      level: '=level',
      qindex: '=qindex',
      pqindex: '=pqindex',
      gpqindex: '=gpqindex'
    },
    controller: 'PreviewQuestion',
    templateUrl: '../JS/AngularTools/JobRouter/exam/preview.question.html'
  }
})
.directive('labelImage', function(){
  return {
    restrict: 'E',
    scope: {
      obj: '=obj'
    },
    controller: 'QuestionUtility',
    templateUrl: '../JS/AngularTools/JobRouter/exam/label.images.html'
  }
})
.directive('labelAudio', function(){
  return {
    restrict: 'E',
    scope: {
      obj: '=obj'
    },
    controller: 'QuestionUtility',
    templateUrl: '../JS/AngularTools/JobRouter/exam/label.audio.html'
  }
})
.directive('labelVideo', function(){
  return {
    restrict: 'E',
    scope: {
      obj: '=obj'
    },
    controller: 'QuestionUtility',
    templateUrl: '../JS/AngularTools/JobRouter/exam/label.video.html'
  }
})
.directive('textbox', function(){
  return {
    restrict: 'E',
    scope: {
      obj: '=obj'
    },
    controller: 'QuestionUtility',
    templateUrl: '../JS/AngularTools/JobRouter/exam/preview.textbox.html',
    link: function($scope, element){
      $scope.getRealTextAns = function(obj){
        let result = ''
        if (obj !== null){
          result = $scope.swlang.getString(obj)
        }
        return result
      }

      $scope.getMaxScore = function(val){
        let arr = []
        for (let i=0; i<=val; i++){
          arr.push(i)
        }

        return arr
      }
    }
  }
})
.directive('singleChoice', function(){
  return {
    restrict: 'E',
    scope: {
      obj: '=obj'
    },
    controller: 'QuestionUtility',
    templateUrl: '../JS/AngularTools/JobRouter/exam/preview.singlechoice.html',
    link: function($scope, element, attr){
      $scope.getMaxScore = function(){
        return parseFloat(Math.max.apply(null, $scope.obj.choice.map(ch => ch.value)))
      }

      $scope.getScore = function(){
        let result = 0
        let objselect = $scope.obj.choice.find((ch) => ch.id === $scope.obj.answer)

        if ($scope.getMaxScore() != 0){
          if (objselect != undefined && (objselect.value != '' && objselect.value != null)){
            result = parseFloat(objselect.value)
          }
        }

        return result
      }
    }
  }
})
.directive('multiChoice', function(){
  return {
    restrict: 'E',
    scope: {
      obj: '=obj'
    },
    controller: 'QuestionUtility',
    templateUrl: '../JS/AngularTools/JobRouter/exam/preview.multichoice.html',
    link: function($scope, element, attr){
      $scope.getMaxScore = function(){
        return $scope.obj.value
      }

      $scope.getScore = function(){
        let result = 0
        let chkobj = $scope.obj.choice.find((data) => {
          return data.isanswer != data.answer
        })

        if (chkobj === undefined){
          result = $scope.obj.value
        }

        return result
      }
    }
  }
})
.directive('sortSentence', function(){
  return {
    restrict: 'E',
    scope: {
      obj: '=obj'
    },
    controller: 'QuestionUtility',
    templateUrl: '../JS/AngularTools/JobRouter/exam/preview.sortsentence.html',
    link: function($scope, element, attr){
      $scope.getMaxScore = function(){
        let result = 0
        if ($scope.obj.value != undefined && $scope.obj.value != null && $scope.obj.value != ''){
          result = parseInt($scope.obj.value)
        }
        return result
      }

      $scope.getScore = function(){
        let result = 0

        if ($scope.getMaxScore() != 0 && $scope.checkAnswer() == undefined){
          result = parseInt($scope.obj.value)
        }

        return result
      }

      $scope.checkAnswer = function(){
        return $scope.obj.sentence.find((data) => {
          return data.answer != data.value
        })
      }

    }
  }
})
.directive('pairText', function(){
  return {
    restrict: 'E',
    scope: {
      obj: '=obj'
    },
    controller: 'QuestionUtility',
    templateUrl: '../JS/AngularTools/JobRouter/exam/preview.pairtext.html',
    link: function($scope, element, attr){
      $scope.getTextRight = function(ansid){
        let result = ''
        if (ansid != undefined && ansid != ''){
          result = $scope.obj.right.find((obj) => obj.id === ansid)
        }

        return $scope.swlang.getString(result.label)
      }

      $scope.getMaxScore = function(){
        let result = 0

        if ($scope.obj.value != undefined && $scope.obj.value != null && $scope.obj.value != ''){
          result = parseInt($scope.obj.value)
        }

        return result
      }

      $scope.getScore = function(){
        let result = 0

        if ($scope.getMaxScore() !=0 && $scope.checkAnswer() == undefined){
          result = $scope.getMaxScore()
        }

        return result
      }

      $scope.checkAnswer = function(){
        return $scope.obj.left.find((data) => {
          return data.answer != data.value
        })
      }
    }
  }
})
.directive('pairPicture', function($sce){
  return {
    restrict: 'E',
    scope: {
      obj: '=obj'
    },
    controller: 'QuestionUtility',
    templateUrl: '../JS/AngularTools/JobRouter/exam/preview.pairpicture.html',
    link: function($scope, element, attr){

      $scope.getLinkImagesLeft = function(obj){
        return $sce.trustAsResourceUrl(`../EXAM/${viewproperty.pairpicture.left}/${obj.picture}`)
      }

      $scope.getLinkImagesRight = function(answer){
        let result = {}
        if (answer != undefined){
          result = $scope.obj.right.find((obj) => obj.id === answer )
        }

        return $sce.trustAsResourceUrl(`../EXAM/${viewproperty.pairpicture.right}/${result.picture}`)
      }

      $scope.getMaxScore = function(){
        let result = 0

        if ($scope.obj.value != undefined && $scope.obj.value != null && $scope.obj.value != ''){
          result = parseInt($scope.obj.value)
        }

        return result
      }

      $scope.getScore = function(){
        let result = 0

        if ($scope.getMaxScore() != 0 && $scope.checkAnswer() == undefined){
          result = $scope.getMaxScore()
        }

        return result
      }

      $scope.checkAnswer = function(){
        return $scope.obj.left.find((data) => {
          return data.answer != data.value
        })
      }
    }
  }
})
.directive('pairPictureText', function($sce){
  return {
    restrict: 'E',
    scope: {
      obj: '=obj'
    },
    controller: 'QuestionUtility',
    templateUrl: '../JS/AngularTools/JobRouter/exam/preview.pairpicturetext.html',
    link: function($scope, element, attr){

      $scope.getLinkImages = function(obj){
        return $sce.trustAsResourceUrl(`../EXAM/${viewproperty.pairpicture.lefttext}/${obj.picture}`)
      }

      $scope.getMaxScore = function(){
        let result = 0

        if ($scope.obj.value != undefined && $scope.obj.value != null && $scope.obj.value != ''){
          result = parseInt($scope.obj.value)
        }

        return result
      }

      $scope.getScore = function(){
        let result = 0

        if ($scope.getMaxScore() != 0 && $scope.checkAnswer() == undefined){
          result = parseInt($scope.obj.value)
        }

        return result
      }

      $scope.checkAnswer = function(){
        return $scope.obj.left.find((data) => {
          return data.answer != data.value
        })
      }

      $scope.getTextRight = function(answer){
        let result = ''
        let robj = $scope.obj.right.find((data) => {
          return data.id === answer
        })

        if (robj != undefined){
          result = robj
        }
        return $scope.swlang.getString(result.label)
      }
    }
  }
})