from lofar.calibration.common.datacontainers import *
import os
from glob import glob



def is_observation_in_range(start, end, from_datetime, to_datetime):
    """
    Checks if a given observation with start and end time happened in the time range specified.
    :param start: start time of the observation
    :param end: end time of the observation
    :param from_datetime: beginning of the time range
    :param to_datetime: end of the time range
    :return: true if the observation is contained in the range false otherwise
    :raises: ValueError if start > end
    """
    if start > end:
        raise ValueError('start datetime is greater then end datetime')

    start_in_range = from_datetime < start < to_datetime
    end_in_range = from_datetime < end < to_datetime

    return start_in_range and end_in_range


def match_holography_beam_specification_file_with_observation(path):
    bsf_files = HolographySpecification.list_bsf_files_in_path(path)
    observation_list = HolographyObservation.list_observations_in_path(path)
    matched_observation_bsf_pair = []
    for bsf_file in bsf_files:
        bsf_file.read_file()
        for observation in observation_list:
            if is_observation_in_range(observation.start_datetime,
                                       observation.end_datetime,
                                       bsf_file.start_datetime,
                                       bsf_file.end_datetime):
                matched_observation_bsf_pair.append(
                    (bsf_file, observation)
                )
    return matched_observation_bsf_pair


def list_all_target_stations(observation_path):
    bsf_files = HolographySpecification.list_bsf_files_in_path(observation_path)
    target_station_name_set = set()
    for bsf_file in bsf_files:
        bsf_file.read_file()
        target_station_name_set.update(bsf_file.target_station_names)
    return list(target_station_name_set)