/* ----------------------------------------------------------------------------
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 qaFile = './public/qa'

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

const writeAfter = 1 // write after # of adds FIXME: set reasonable save rate
var currWrites = 0

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

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

  try {
    // recievedData: { version: "", id: "", subj: "" quiz: {} }
    let d = JSON.parse(recievedData)
    let allQLength = d.quiz.length
    let allQuestions = []

    d.quiz.forEach((question) => {
      let q = new classes.Question(question.Q, question.A, question.data)
      let sames = qdb.Search(q, d.subj)
      // if it didnt find any question, or every found questions match is lower thatn 80
      let isNew = sames.length === 0 || sames.every(searchResItem => {
        return searchResItem.match < classes.minMatchAmmount
      })
      if (isNew) {
        allQuestions.push(q)
      }
    })

    let color = logger.GetColor('green')
    let msg = ''
    if (allQuestions.length > 0) {
      color = logger.GetColor('blue')
      msg += `New questions: ${allQuestions.length} ( All: ${allQLength} )`

      allQuestions.forEach((q) => {
        qdb.AddQuestion(d.subj, q)
      })

      currWrites++
      console.log(currWrites)
      if (currWrites >= writeAfter) {
        currWrites = 0
        try {
          qdb.version = infos.version
          qdb.motd = infos.motd
        } catch (e) {
          logger.Log('MOTD/Version writing/reading error!')
        }
        utils.WriteFile(JSON.stringify(qdb), dataFile)
        logger.Log('\tData file written', color)
      }
    } else {
      msg += `No new data ( ${allQLength} )`
    }

    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)
    return allQuestions.length
  } catch (e) {
    console.log(e)
    logger.Log('Couldnt parse JSON data', logger.GetColor('redbg'))
    return -1
  }
}

// loading stuff
function LoadJSON (dataFile) {
  try {
    var d = JSON.parse(utils.ReadFile(dataFile))
    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.data))
      }
      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)
    console.log(e)
  }
}

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
}