const util = require("../util")

// Electron
const { dialog } = require('electron').remote
const { ipcRenderer } = require('electron')
const fs = require('fs')
const path = require('path')
const $ = require('jquery')
var Jimp = require('jimp');

var shell = require('electron').shell;
//open links externally by default
$(document).on('click', 'a[href^="http"]', function (event) {
  event.preventDefault();
  shell.openExternal(this.href);
});

const getLang = ipcRenderer.sendSync('ipcSyncMF_getLanguage')
const initDict = getLang.current
const defaultDict = getLang.default

// Framework7
const $$ = Dom7
const framework = new Framework7({
  theme: 'aurora',
  root: '#app',
  name: 'CURIO',
  id: 'com.dandyunicorns.curio',
  data: function () {
    return {
      appdict: initDict.app,
      gamedict: initDict.game
    }
  },
  dialog: {
    buttonOk: initDict.app.btn_ok,
    buttonCancel: initDict.app.btn_cancel
  },
  routes: [
    {
      name: 'home',
      path: '/home/',
      componentUrl: './pages/home.html',
    }, {
      name: 'manage_class',
      path: '/manage_class/',
      componentUrl: './pages/manage_class.html',
    }, {
      name: 'manage_scenario',
      path: '/manage_scenario/',
      componentUrl: './pages/manage_scenario.html',
    }, {
      name: 'manage_translation',
      path: '/manage_translation/',
      componentUrl: './pages/manage_translation.html',
    }, {
      name: 'waiting',
      path: '/game1_waiting/',
      componentUrl: './pages/game1_waiting.html',
    }, {
      name: 'beginning',
      path: '/game2_beginning/',
      componentUrl: './pages/game2_beginning.html',
    }, {
      name: 'phase1',
      path: '/game3_phase1/',
      componentUrl: './pages/game3_phase1.html',
    }, {
      name: 'phase2',
      path: '/game4_phase2/',
      componentUrl: './pages/game4_phase2.html',
    }, {
      name: 'phase34',
      path: '/game5_phase34/',
      componentUrl: './pages/game5_phase34.html',
    }, {
      name: 'phase5',
      path: '/game6_phase5/',
      componentUrl: './pages/game6_phase5.html',
    }, {
      name: 'endgame1',
      path: '/endgame1_intro/',
      componentUrl: './pages/endgame1_intro.html',
    }, {
      name: 'endgame2',
      path: '/endgame2_attack/',
      componentUrl: './pages/endgame2_attack.html',
    }, {
      name: 'endgame3',
      path: '/endgame3_attackresolve/',
      componentUrl: './pages/endgame3_attackresolve.html',
    }, {
      name: 'endgame4',
      path: '/endgame4_resolution/',
      componentUrl: './pages/endgame4_resolution.html',
    }, {
      name: 'endgame5',
      path: '/endgame5_stickers/',
      componentUrl: './pages/endgame5_stickers.html',
    }
  ],
  on: {
    init: function () {
      console.log('App initialized')
    },
    pageInit: function () {
      console.log('Page initialized');

    }
  },
})


var mainView = framework.views.create('.view-main', {
  url: '/home/',
  // url: '/manage_scenario_create/',
  preloadPreviousPage: false
})

let ui = {
  publicUrl: ipcRenderer.sendSync('ipcSyncMF_getPublicUrl'),
  fn: {},
  lastUpdate: null,
  timer: null,
  timerPause: false,
  lastTimer: null,
  update: null,
  shotUpdate: null,
  questionQueue: null,
  tmp: {},
  triggerEnd: false,
  endRound: 0,
  manageClass: {},
  manageScenario: {},
  manageLanguage: {}
}

let tmp_game1_playerTable = fs.readFileSync(path.resolve(__dirname, './templates/game1_playertable.tmp7'), "utf8")
let tmp_game5_questionCard = fs.readFileSync(path.resolve(__dirname, './templates/game5_questioncard.tmp7'), "utf8")
let tmp_manageScenario_subtopic = fs.readFileSync(path.resolve(__dirname, './templates/manageScenario_subtopic.tmp7'), "utf8")

ui.tmp.game1_playerTable = Template7.compile(tmp_game1_playerTable)
ui.tmp.game5_questionCard = Template7.compile(tmp_game5_questionCard)
ui.tmp.manageScenario_subtopic = Template7.compile(tmp_manageScenario_subtopic)


ui.tmp.screenShot = `
  <div class="bg-moon-gray flex justify-center relative overflow-hidden br2" style="padding-bottom: 56.25%">
  <div class="screenShotDisplay absolute flex flex-column justify-center h-100">
    <div class="preloader" style="margin: 0 auto; width: 44px; height: 44px"></div>
    <div class="mt3 gray b">${framework.data.appdict.label_liveview}</div>
  </div>
  </div>
`



ui.fn.timerUpdate = function () {
  let now = Date.now()
  let dt = (now - ui.lastUpdate) * 0.001
  ui.lastUpdate = now

  if (!ui.timerPause) ui.timer -= dt
  if (ui.timer < 0) ui.timer = 0

  let intTimer = Math.floor(ui.timer)
  if (intTimer != ui.lastTimer) {
    // Sending new timer value
    ipcRenderer.send('ipcF2M_setGameTimer', intTimer)
    ui.lastTimer = intTimer
  }

  return intTimer
}

ui.fn.nextPhase = function () {

  clearInterval(ui.shotUpdate)
  clearInterval(ui.update)


  let current = mainView.router.currentRoute.name
  let next = ''
  if (current === 'waiting') next = 'beginning'
  else if (current === 'beginning') next = 'phase1'
  else if (current === 'phase1') next = 'phase2'
  else if (current === 'phase2') next = 'phase34'
  else if (current === 'phase34') next = 'phase5'
  else if (current === 'phase5') next = 'phase1'

  else if (current === 'endgame1') next = 'endgame2'

  else if (current === 'endgame2') next = 'endgame3'
  else if (current === 'endgame3') next = 'endgame2'

  else if (current === 'endgame4') next = 'endgame5'

  mainView.router.navigate({ name: next })
}

ui.fn.triggerEndgame = function () {
  clearInterval(ui.shotUpdate)
  clearInterval(ui.update)

  mainView.router.navigate({ name: 'endgame1' })
  ui.triggerEnd = false
}

ui.fn.checkAndTriggerEndresolution = function () {
  console.log(`Now at endround ${ui.endRound}`)

  if (ui.endRound < 2) {
    ui.endRound += 1
    ui.fn.nextPhase()
  } else {
    clearInterval(ui.shotUpdate)
    clearInterval(ui.update)
    mainView.router.navigate({ name: 'endgame4' })
  }

}

ui.fn.triggerPhase4 = function () {
  $$(".game5-title-span").html(framework.data.appdict.game5_title_phase4)
  $$("#game5-info-span").html(framework.data.appdict.game5_info_phase4)

  $$("#phase3-block").hide()
  $$("#phase4-block").show()

  ui.timerPause = true

  ipcRenderer.send('ipcF2M_setGameState', 'Phase4')
  ipcRenderer.send('ipcF2M_getAcceptedQuestions_pushToClients')

}

ui.fn.updateScreenShot = function () {
  ipcRenderer.send('ipcF2M_requestScreenshot')
}





ipcRenderer.on('ipcM2F_dialogAlert', (event, arg) => {
  framework.dialog.alert(arg)
})

ipcRenderer.on('ipcM2F_refreshFrontend', (event, arg) => {
  mainView.router.refreshPage()
})

ipcRenderer.on('ipcM2F_showScreenshot', (event, arg) => {

  Jimp.read(Buffer.from(arg))
    .then(image => {
      image.getBase64(Jimp.AUTO, function (err, src) {

        $$(".screenShotDisplay").html(`<img src="${src}">`)

      })
    })

})


// Game4 - Phase2
ipcRenderer.on('ipcM2F_moveVoteResults', (event, arg) => {
  // Use these in the teacher UI
  console.log(arg)

  if (arg.winner === arg.endnode) {
    ui.triggerEnd = true
    console.log("Next phase will be endphase!")
  }

})

// Game5 - Phase34
ipcRenderer.on('ipcM2F_checkAttachedQuestions', (event, arg) => {
  $$("#loader-block").hide()

  ui.questionQueue = arg.length

  let questionInfo = { item: arg, appdict: framework.data.appdict }

  let compiledHTML = ui.tmp.game5_questionCard(questionInfo)
  $$("#questionroot").html(compiledHTML)

  $$('.acceptButton').on('click', function (e) {
    let qitem = $$(this).closest('.question-item')
    let qid = qitem.attr('data-id')
    let username = qitem.attr('data-byuser')

    console.log(`ACCEPTED ${qid} by ${username}`)

    qitem.animate({ 'opacity': 0, 'height': 0 }, {
      complete: function (e) {
        qitem.remove()
        ipcRenderer.send('ipcF2M_updateQuestionState', { id: qid, state: 'ACCEPTED', username: username })
        ui.questionQueue -= 1
      }
    })
  })

  $$('.rejectButton').on('click', function (e) {
    let qitem = $$(this).closest('.question-item')
    let qid = qitem.attr('data-id')
    console.log("REJECTED " + qid)

    qitem.animate({ 'opacity': 0, 'height': 0 }, {
      complete: function (e) {
        qitem.remove()
        ipcRenderer.send('ipcF2M_updateQuestionState', { id: qid, state: 'REJECTED' })
        ui.questionQueue -= 1
      }
    })
  })

})

