#[Copyright 2024 ITwrx.
This file is part of Simple Site Manager.
Simple Site Manager is released under the GNU Affero General Public License 3.0.
See COPYING or <https://www.gnu.org/licenses/> for details.]#

import sqliteral, "../helpers/db", "../helpers/global.nim", sequtils

type
  Reminder* = object
    title*, message*, notifyVia*, repeatFreq*, sendDate*, sendTimeAmPm*, monthlyOnWeek*, yearlyOnWeek*, weeklyOn*, monthlyOnWeekday*, yearlyOnMonth*, yearlyOnWeekday*, yearlyOnMonth2*: string
    id*, repeats*, monthlyOnDay*, yearlyOnDay*, sendTimeHr*, sendTimeMin*: int

var allReminders: seq[Reminder]

proc getAllReminders*(): seq[Reminder] =
  {.gcsafe.}:
    if allReminders.len == 0:
      for row in db1.rows(SelectAllReminders):
        allReminders.add(Reminder(id: row.getInt(0), title: row.getString(1), message: row.getString(2), notifyVia: row.getString(3), repeats: row.getInt(4), repeatFreq: row.getString(5), weeklyOn: row.getString(6), monthlyOnDay: row.getInt(7), monthlyOnWeekday: row.getString(8), monthlyOnWeek: row.getString(9), yearlyOnMonth: row.getString(10), yearlyOnDay: row.getInt(11), yearlyOnWeek: row.getString(12), yearlyOnWeekday: row.getString(13), yearlyOnMonth2: row.getString(14), sendDate: row.getString(15), sendTimeHr: row.getInt(16), sendTimeMin: row.getInt(17), sendTimeAmPm: row.getString(18)))
    return allReminders

proc clearAllReminders*() =
  {.gcsafe.}:
    allReminders.setLen(0)

proc getReminderById*(id: int): Reminder =
  {.gcsafe.}:
    for reminder in getAllReminders():
      if reminder.id == id:
        return reminder

proc createReminder*(reminder: Reminder): int =
  {.gcsafe.}:
    var reminderId: int
    db1.transaction:
      reminderId = db1.insert(InsertReminder, reminder.title, reminder.message, reminder.notifyVia, reminder.repeats, reminder.repeatFreq, reminder.weeklyOn, reminder.monthlyOnDay, reminder.monthlyOnWeekday, reminder.monthlyOnWeek, reminder.yearlyOnMonth, reminder.yearlyOnDay, reminder.yearlyOnWeek, reminder.yearlyOnWeekday, reminder.yearlyOnMonth2, reminder.sendDate, reminder.sendTimeHr, reminder.sendTimeMin, reminder.sendTimeAmPm)
    return reminderId

proc updateReminder*(reminder: Reminder) =
  {.gcsafe.}:
    db1.transaction:
      db1.exec(UpdateReminder, reminder.title, reminder.message, reminder.notifyVia, reminder.repeats, reminder.repeatFreq, reminder.weeklyOn, reminder.monthlyOnDay, reminder.monthlyOnWeekday, reminder.monthlyOnWeek, reminder.yearlyOnMonth, reminder.yearlyOnDay, reminder.yearlyOnWeek, reminder.yearlyOnWeekday, reminder.yearlyOnMonth2, reminder.sendDate, reminder.sendTimeHr, reminder.sendTimeMin, reminder.sendTimeAmPm, reminder.id)

proc updateReminderSendDate*(reminder: Reminder) =
  {.gcsafe.}:
    db1.transaction:
      db1.exec(UpdateReminderSendDate, reminder.sendDate, reminder.id)

proc deleteReminder*(id: int) =
  {.gcsafe.}:
    db1.transaction:
      db1.exec(DeleteReminder, id)
