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

 Question Server
 GitLab: <https://gitlab.com/MrFry/question-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 = {
  LogStat: LogStat,
  Load: Load
}

var utils = require('../utils/utils.js')
var logger = require('../utils/logger.js')

const statFile = 'stats/stats'
const vStatFile = 'stats/vstats'
const writeInterval = 10

var data = {}
var vData = {}
var writes = 0

function Load () {
  try {
    var prevData = utils.ReadFile(statFile)
    data = JSON.parse(prevData)
  } catch (e) {
    logger.Log('Error at loading logs! (@ first run its normal)', logger.GetColor('redbg'))
    console.log(e)
  }

  try {
    var prevVData = utils.ReadFile(vStatFile)
    vData = JSON.parse(prevVData)
  } catch (e) {
    logger.Log('Error at loading visit logs! (@ first run its normal)', logger.GetColor('redbg'))
    console.log(e)
  }
}

function LogStat (url) {
  url = url.split('?')[0]
  Inc(url)
  AddVisitStat(url)
  Save()
}

function Inc (value) {
  if (value.startsWith('/?')) { value = '/' }
  if (data[value] === undefined) { data[value] = 0 }
  data[value]++
}

function AddVisitStat (name) {
  var m = new Date()
  const now = m.getFullYear() + '/' + ('0' + (m.getMonth() + 1)).slice(-2) + '/' + ('0' + m.getDate()).slice(-2)
  if (vData[now] === undefined) { vData[now] = {} }
  if (vData[now][name] === undefined) { vData[now][name] = 0 }
  vData[now][name]++
}

function Save () {
  writes++
  if (writes === writeInterval) {
    try {
      utils.WriteFile(JSON.stringify(data), statFile)
      // logger.Log("Stats wrote.");
    } catch (e) {
      logger.Log('Error at writing logs!', logger.GetColor('redbg'))
      console.log(e)
    }
    try {
      utils.WriteFile(JSON.stringify(vData), vStatFile)
      // logger.Log("Stats wrote.");
    } catch (e) {
      logger.Log('Error at writing visit logs!', logger.GetColor('redbg'))
      console.log(e)
    }
    writes = 0
  }
}