# 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 sys
from xml.dom.minidom import getDOMImplementation  # nosec
import xml.parsers.expat

from defusedxml import minidom

from EmailReminder.Anniversary import AnniversaryModel
from EmailReminder.Birthday import BirthdayModel
from EmailReminder.Monthly import MonthlyModel
from EmailReminder.Utils import readXMLValue, writeXMLValue
from EmailReminder.Weekly import WeeklyModel
from EmailReminder.Yearly import YearlyModel


class EventList:
    SUPPORTED_TYPES = ('birthday', 'anniversary', 'yearly', 'monthly',
                       'weekly')

    def __init__(self, simulate, verbose):
        self.stores = {}
        self.filename = None
        self.document = None
        self.user = None

        self.simulate = simulate
        self.verbose = verbose

    def _createDocument(self):
        self.document = getDOMImplementation().createDocument(
            None, 'email-reminder_user', None)

    def getUser(self):
        user = {}

        if not self.user:
            return user
        for field in ('first_name', 'last_name', 'email'):
            user[field] = readXMLValue(self.user, field)

        return user

    def setUser(self, user):
        for field in ('first_name', 'last_name', 'email'):
            if field in user:
                writeXMLValue(self.document, self.user, field, user[field])

    def load(self, filename):
        self.filename = filename
        if self.verbose:
            print(f"Loading events from {self.filename}")
        try:
            with open(self.filename, encoding='utf-8') as fh:
                try:
                    self.document = minidom.parseString(fh.read())
                except xml.parsers.expat.ExpatError as err:
                    if err.code == 3:  # no elements
                        self._createDocument()
                    else:
                        print(f"Error: '{filename}' is not a valid "
                              f"configuration file ({err})", file=sys.stderr)
                        return False
        except FileNotFoundError:
            self._createDocument()

        users = self.document.getElementsByTagName('email-reminder_user')
        self.user = users.item(0)

        events = self.user.getElementsByTagName('events')
        if events:
            events = events.item(0)
        else:
            events = self.document.createElement('events')
            self.document.documentElement.appendChild(events)

        for event in events.getElementsByTagName('event'):
            for eventType in self.SUPPORTED_TYPES:
                if event.getAttribute('type') == eventType:
                    self.model(eventType).addEvent(event)
                    break

        return True

    def save(self):
        if not self.document:
            return
        if self.simulate:
            return

        if self.verbose:
            print(f"Writing events to {self.filename}")

        with open(self.filename, mode='w', encoding='utf-8') as fh:
            fh.write(self.document.toxml())  # TODO: use toprettyxml()?

    def model(self, eventType):
        if eventType not in self.stores:
            if eventType == 'anniversary':
                self.stores[eventType] = AnniversaryModel(self.document)
            elif eventType == 'birthday':
                self.stores[eventType] = BirthdayModel(self.document)
            elif eventType == 'yearly':
                self.stores[eventType] = YearlyModel(self.document)
            elif eventType == 'monthly':
                self.stores[eventType] = MonthlyModel(self.document)
            elif eventType == 'weekly':
                self.stores[eventType] = WeeklyModel(self.document)
        return self.stores[eventType]
