#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: nu:ai:ts=4:sw=4

#
#  Copyright (C) 2024 Joseph Areeda <joseph.areeda@ligo.org>
#
#  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/>.
#
"""
Class representing a channel metadata and data stream
"""

__author__ = 'joseph areeda'
__email__ = 'joseph.areeda@ligo.org'

import logging

from gwpy.io.datafind import find_best_frametype
from gwpy.time import to_gps, tconvert
from lal import LIGOTimeGPS
from ligotimegps import LIGOTimeGPS


class Channel:
    meta_gps: LIGOTimeGPS
    name: str

    def __init__(self, name, gps, logger=None):
        """

        :param str name: Channel name
        :param str|int|LIGOTimeGPS gps: A gps time to use to get metadata (not a timeseries)
        :param logging.Logger logger:
        """
        self.name = name
        self.meta_gps = to_gps(gps)

        if logger is None:
            logging.basicConfig()
            self.logger = logging.getLogger("GWF")
            self.logger.setLevel(logging.INFO)
        else:
            self.logger = logger
        self.logger: logging.Logger

        self.frame_type = None
        self.get_frame_type()

        self.get_metadata(name, gps)

    def get_metadata(self, name, gps):
        """
        Learn what we can about this channel
        :param str name: Channel name
        :param str|int|LIGOTimeGPS gps: A gps time to use to get metadata (not a timeseries)
        :return:
        """
        pass

    def get_frame_type(self):
        """determine best frame type for this channel """
        if self.frame_type is not None:
            ret = self.frame_type
        else:
            try:
                ret = find_best_frametype(self.name, self.meta_gps, self.meta_gps+1)
            except ValueError as ex:
                self.logger.info(f'No frame type found for {self.name} at '
                                 f'{int(self.meta_gps)} {tconvert(self.meta_gps)}')
