from numpy.typing import ArrayLike
from typing import List, AnyStr
from numpy import matrix
from typing import List
import re
from io import StringIO
import numpy as np

import pandas as pd
import math

from scipy import constants as consts

from spatz.sensors import Sensor
from spatz.simulation import Simulation
from spatz.transforms import Transform
from spatz.dataset import Dataset
from spatz.logger import Logger
import time



'''

Estimats the free-space path loss (FSPL) in dB
https://de.wikipedia.org/wiki/Freiraumd%C3%A4mpfung

Used formulas:
FSPL = ((4*pi*d*f)/c)^2
FSPL_db = 20*log10((4*pi*d*f)/c)
c = sciply.constants.c


Parameters:
 - Frequency: duh
 - RX antenna offset: offset of the recieving antenna from the launchrail in Launcher frame. (Z is up, Y is north, X is east )
'''


class AntennaPathloss(Sensor):
    def __init__(self, dataset: Dataset, logger: Logger, transforms: List[Transform] = [], frequency:float = 2.45e9, rx_antenna_offset: ArrayLike = np.array([0,0,0])):
        super().__init__(dataset, logger, transforms)
        self.__freq = frequency
        self.__lambda = self.__freq/consts.c
        self.__rx_offset = rx_antenna_offset


    def _get_data(self) -> ArrayLike | float:
        #Get rocket position
        pos_fl = self._dataset.fetch_values(['x','y','z']) # X,Y,Z position in launcher frame. Z is upm, X is east

        #Get connection vector
        rocket_to_gs_fl = pos_fl - self.__rx_offset

        #Get distance
        dist = np.linalg.norm(rocket_to_gs_fl)
        self._log("distance",dist)

        #Calc FSPL
        FSPL_db = 20.0 * np.log10(np.pi*4*dist*self.__lambda)

        return FSPL_db    
    
    def _sensor_specific_effects(self, x: ArrayLike) -> ArrayLike:
        return x
    
    def _get_name(self) -> AnyStr:
        return 'antenna/pathloss'