# __init__.py
#
# Copyright 2020-2022 Fabio Comuni, et al.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
from ..fetcher import Fetcher
from .exceptions import InvalidFormatException
from .pentabarf import import_pentabarf
from .ics import import_ics
from gettext import gettext as _


def update_schedule(url: str) -> Fetcher:
    def _do_load(sender, local_filename: str):
        print("local conf file:", local_filename)
        with open(local_filename, "r") as f:
            content = f.read()
        if content.strip().startswith("<"):
            import_pentabarf(content, url)
        elif content.strip().startswith("BEGIN:VCALENDAR"):
            import_ics(content, url)
        else:
            raise InvalidFormatException(_("Unknown schedule format"))
        os.remove(local_filename)

    return Fetcher(url, cbk=_do_load)
