# This file is part of Email-Reminder.
#
# Copyright (C) 2020 by Francois Marier
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

import datetime

from EmailReminder.Event import EventModel
from EmailReminder.Utils import readXMLValue, writeXMLValue


def formatDate(year, month, day):
    if not month or not day:
        return ''

    try:
        if not year:
            # 1980 is a leap year
            return datetime.date(1980, int(month), int(day)).strftime('%m-%d')
        return datetime.date(int(year), int(month), int(day)).isoformat()
    except ValueError:
        return ''


def parseDate(dateString):
    try:
        if len(dateString) == 5:
            date = datetime.datetime.strptime(dateString, '%m-%d')
            return {'year': None, 'month': date.month, 'day': date.day}
        date = datetime.datetime.strptime(dateString, '%Y-%m-%d')
    except ValueError:
        date = datetime.datetime.today()

    return {'year': date.year, 'month': date.month, 'day': date.day}


class YearlyModel(EventModel):
    LABEL = 'Yearly Events'
    TYPE = 'yearly'
    COLUMN_NAMES = ["Event Name", "Event Date"]

    def fillNewEvent(self, event):
        super().fillNewEvent(event)

        writeXMLValue(self.document, event, 'month', 1)
        writeXMLValue(self.document, event, 'day', 15)

    def getDataInternal(self, column, row):
        parentData = super().getDataInternal(column, row)
        if parentData:
            return parentData
        if column == 1:
            event = self.events[row]
            year = readXMLValue(event, 'year')
            month = readXMLValue(event, 'month')
            day = readXMLValue(event, 'day')
            return formatDate(year, month, day)

        return None

    def setDataInternal(self, column, row, value):
        if column == 1:
            event = self.events[row]
            date = parseDate(value)
            writeXMLValue(self.document, event, 'year', date['year'])
            writeXMLValue(self.document, event, 'month', date['month'])
            writeXMLValue(self.document, event, 'day', date['day'])
        else:
            super().setDataInternal(column, row, value)
