/* ----------------------------------------------------------------------------
Question Server
 GitLab: <https://gitlab.com/MrFry/mrfrys-node-server>

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program. If not, see <https://www.gnu.org/licenses/>.

 ------------------------------------------------------------------------- */

module.exports = {
  ProcessIncomingRequest: ProcessIncomingRequest,
  LoadJSON: LoadJSON,
  ProcessQA: ProcessQA
}

const dataFile = './public/data.json'
const recDataFile = './stats/recdata'
const versionFile = './public/version'
const motdFile = './public/motd'
const qaFile = './public/qa'

var logger = require('../utils/logger.js')
const idStats = require('../utils/ids.js')
idStats.Load() // TODO: dont always load when actions.js is used
var utils = require('../utils/utils.js')
const classes = require('./question-classes/classes.js')

function ProcessIncomingRequest (data) {
  if (data === undefined) {
    logger.Log('\tRecieved data is undefined!', logger.GetColor('redbg'))
    return
  }

  try {
    let towrite = logger.GetDateString() + '\n'
    towrite += '------------------------------------------------------------------------------\n'
    towrite += data
    towrite += '\n------------------------------------------------------------------------------\n'
    utils.AppendToFile(towrite, recDataFile)
  } catch (e) {
    logger.log('Error writing recieved data.')
  }

  try {
    var d = JSON.parse(data)
    var allQuestions = []
    for (let i = 0; i < d.allData.length; i++) {
      allQuestions.push(new classes.Question(d.allData[i].Q, d.allData[i].A, d.allData[i].I))
    }

    let color = logger.GetColor('green')
    let questions = []
    let msg = ''
    if (d.data.length > 0) {
      msg += `New questions: ${d.data.length} ( All: ${allQuestions.length} )`
    } else {
      msg += `No new data ( ${allQuestions.length} )`
    }
    if (d.data.length > 0) {
      let qdb = LoadJSON(utils.ReadFile(dataFile))
      d.data.forEach((x) => {
        let q = new classes.Question(x.Q, x.A, x.I)
        questions.push(q)
        qdb.AddQuestion(d.subj, q)
      })

      try {
        data.version = utils.ReadFile(versionFile)
        data.motd = utils.ReadFile(motdFile)
      } catch (e) {
        logger.Log('MOTD/Version writing/reading error!')
      }

      if (qdb !== undefined && d.data.length > 0) {
        utils.WriteBackup()
        utils.WriteFile(JSON.stringify(qdb), dataFile)
        msg += ' - Data file written!'
        color = logger.GetColor('blue')
      }
    }

    let subjRow = '\t' + d.subj
    if (d.id) {
      subjRow += ' ( CID: ' + logger.logHashed(d.id) + ')'
      idStats.LogId(d.id, d.subj)
    }
    logger.Log(subjRow)
    if (d.version !== undefined) { msg += '. Version: ' + d.version }

    logger.Log('\t' + msg, color)
  } catch (e) {
    console.log(e)
    logger.Log('Couldnt parse JSON data', logger.GetColor('redbg'))
  }
}

// loading stuff
function LoadJSON (resource) {
  try {
    var d = JSON.parse(resource)
    var r = new classes.QuestionDB((x) => true, (x, y) => console.log(x, y))
    var rt = []

    for (var i = 0; i < d.Subjects.length; i++) {
      let s = new classes.Subject(d.Subjects[i].Name)
      var j = 0
      for (j = 0; j < d.Subjects[i].Questions.length; j++) {
        var currQ = d.Subjects[i].Questions[j]
        s.AddQuestion(new classes.Question(currQ.Q, currQ.A, currQ.I))
      }
      rt.push({
        name: d.Subjects[i].Name,
        count: j
      })
      r.AddSubject(s)
    }
    return r
  } catch (e) {
    logger.Log('Error loading sutff', logger.GetColor('redbg'), true)
  }
}

function ProcessQA () {
  if (!utils.FileExists(qaFile)) { utils.WriteFile('', qaFile) }

  let a = utils.ReadFile(qaFile).split('\n')
  let r = []
  let ind = 0
  for (let i = 0; i < a.length; i++) {
    if (a[i] === '#') { ind++ } else {
      if (r[ind] === undefined) { r[ind] = {} }

      if (r[ind].q === undefined) {
        r[ind].q = a[i]
      } else {
        if (r[ind].a === undefined) { r[ind].a = [] }

        r[ind].a.push(a[i])
      }
    }
  }

  return r
}