const { cozyClient } = require('cozy-konnector-libs')
const { rangeDate } = require('./../constants')

/**
 * Aggregates the load data by month, summing the load of each day for each month.
 *
 * @param {import('../types').FormattedData[]} data - The data to aggregate.
 *
 * @returns {import('../types').FormattedData[]} - An array of aggregated data by month.
 */
function aggregateMonthlyLoad(data) {
  const monthlyLoad = {}

  for (const entry of data) {
    const { year, month, load } = entry
    const monthKey = `${year}-${month}`

    if (!monthlyLoad[monthKey]) {
      monthlyLoad[monthKey] = {
        load: load,
        year: year,
        month: month,
        day: 0,
        hour: 0,
        minute: 0
      }
    } else {
      monthlyLoad[monthKey].load += load
    }
  }

  return Object.values(monthlyLoad)
}

/**
 * Aggregates the load data by year, summing the load of each month for each year.
 *
 * @param {import('../types').FormattedData[]} data - The data to aggregate.
 *
 * @returns {import('../types').FormattedData[]} - An array of aggregated data by year.
 */
function aggregateYearlyLoad(data) {
  const yearlyLoad = {}

  for (const entry of data) {
    const { year, load } = entry

    if (!yearlyLoad[year]) {
      yearlyLoad[year] = {
        load: load,
        year: year,
        month: 0,
        day: 0,
        hour: 0,
        minute: 0
      }
    } else {
      yearlyLoad[year].load += load
    }
  }

  return Object.values(yearlyLoad)
}

/**
 * Removes aggregates matching the same year and month as the first data retrieved from GRDF if it is already in database.
 *
 * This step is needed to avoid updating the 3 years old month aggregate with incomplete data
 *
 * @param {number} firstMonth
 * @param {number} firstYear
 * @param {import('../types').FormattedData[]} yearlyLoads
 * @returns {Promise<import('../types').FormattedData[]>}
 */
async function filterFirstMonthlyLoad(firstMonth, firstYear, monthlyLoads) {
  const monthlyLoadRef = await cozyClient.data.defineIndex(
    rangeDate.month.doctype,
    rangeDate.month.keys
  )
  const startDateMonthlyLoad = await cozyClient.data.query(monthlyLoadRef, {
    selector: { year: firstYear, month: firstMonth },
    limit: 1
  })

  if (!startDateMonthlyLoad.length) {
    return monthlyLoads
  }
  return monthlyLoads.filter(
    monthlyLoad =>
      monthlyLoad.year !== startDateMonthlyLoad[0].year ||
      monthlyLoad.month !== startDateMonthlyLoad[0].month
  )
}

/**
 * Removes aggregates matching the same year as the first data retrieved from GRDF if it is already in database.
 *
 * This step is needed to avoid updating the 3 years old year aggregate with incomplete data
 *
 * @param {number} firstYear
 * @param {import('../types').FormattedData[]} yearlyLoads
 * @returns {Promise<import('../types').FormattedData[]>}
 */
async function filterFirstYearlyLoad(firstYear, yearlyLoads) {
  const yearlyLoadRef = await cozyClient.data.defineIndex(
    rangeDate.year.doctype,
    rangeDate.year.keys
  )
  const startDateYearlyLoad = await cozyClient.data.query(yearlyLoadRef, {
    selector: { year: firstYear },
    limit: 1
  })
  if (!startDateYearlyLoad.length) {
    return yearlyLoads
  }
  return yearlyLoads.filter(
    yearlyLoad => yearlyLoad.year !== startDateYearlyLoad[0].year
  )
}

module.exports = {
  aggregateMonthlyLoad,
  aggregateYearlyLoad,
  filterFirstMonthlyLoad,
  filterFirstYearlyLoad
}