# 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 re

EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+")


def readXMLValue(parent, name):
    element = None
    for candidate in parent.getElementsByTagName(name):
        element = candidate
        if candidate.parentNode == parent:
            break  # found the right node
        element = None  # keep looking

    if not element:
        return None
    if not element.firstChild:
        return None
    return element.firstChild.nodeValue


def writeXMLValue(document, parent, name, value):
    element = None
    for candidate in parent.getElementsByTagName(name):
        element = candidate
        if candidate.parentNode == parent:
            break  # found the right node
        element = None  # keep looking

    if not value:
        if element:
            parent.removeChild(element)
        return

    if not element:
        element = document.createElement(name)
        element.appendChild(
            document.createTextNode(str(value)))
        parent.appendChild(element)
        return

    if not element.hasChildNodes():
        element.appendChild(
            document.createTextNode(str(value)))
        return

    element.firstChild.nodeValue = str(value)
