# Copyright 2021-2022 Teemu Ikonen
# SPDX-License-Identifier: GPL-3.0-only

import re

from datetime import datetime, timezone

from .util import (
    datetime_from_gpstime,
    gps_epoch,
    gpstime_from_datetime,
)


def get_constellations(source):
    i2constellations = {
        0: [],
        1: ["Glonass", "BeiDou", "Galileo"],
        2: ["Glonass", "BeiDou"],
        3: ["Glonass", "Galileo"],
        4: ["Glonass"],
        5: ["BeiDou", "Galileo"],
        6: ["Galileo"],
    }
    try:
        r = source.modem.Command('AT+QGPSCFG="gnssconfig"', 3)
        mo = re.match(r'\+QGPSCFG: "gnssconfig",(?P<ind>\d)', r)
    except Exception:
        mo = None

    if not mo:
        return None
    return ["GPS"] + i2constellations.get(int(mo.group('ind')))


def get_xtradata_dates(source, fix_week=False):
    try:
        r = source.modem.Command('AT+QGPSXTRADATA?', 3)
        # Example reply: '+QGPSXTRADATA: 10080,"2002/01/18,12:00:00"'
        mo = re.match(
            r'\+QGPSXTRADATA: (?P<duration>\d+),"(?P<time>[^"]+)"', r)
    except Exception:
        mo = None

    if not mo:
        return None
    dur_min = int(mo.group('duration'))
    datestr = mo.group('time').replace('/', '-').replace(',', 'T')
    startdt = datetime.fromisoformat(datestr + "+00:00")
    if fix_week and startdt > gps_epoch:
        week, ms = gpstime_from_datetime(startdt)
        startdt = datetime_from_gpstime(week, ms, fix_week=True)

    enddt = datetime.fromtimestamp(startdt.timestamp() + dur_min * 60,
                                   timezone.utc)
    return startdt, enddt
