from ctypes import *
from numpy.ctypeslib import ndpointer
import yaml
import pyproj

esa_sat_list = 'esa_sat_list.yml'
metadata_file = 'metadata.yml'
so_file_satellite = "../eocfi_c/bin/get_positions.so"

eocfi_sat = CDLL(so_file_satellite)

date_structure = {'y': 2022,
                  'm': 1,
                  'd': 2,
                  'hh': 00,
                  'mm': 00,
                  'ss': 00}

# Helper function to turn Python list of Unicode strings
# into a ctypes array of byte strings.
def make_clist(lst):
    return (c_char_p * len(lst))(*[x.encode() for x in lst])

sat_list = yaml.load(open(esa_sat_list), Loader=yaml.FullLoader)

sat = "SENTINEL_5P"
sat_data = sat_list.get(sat)
sat_id = sat_data['id']
sat_n_files = sat_data['n_files']
sat_orbit_files = sat_data['orbit_files']
# hay que hacer que esto sea un array
orbit_files = []
for file in range(sat_n_files):
    orbit_file = f"data/mission_configuration_files/{sat_orbit_files[file]}"
    #orbit_file = orbit_file.encode()
    orbit_files.append(orbit_file)

metadata = yaml.load(open(metadata_file), Loader=yaml.FullLoader)

bulletin = metadata.get("BULLETIN_IERS")["file"]

bulletinb_file_init_time = bulletin.encode()

eocfi_sat.get_moon_position.restype = ndpointer(dtype=c_double, shape=(3,))
moon_position = eocfi_sat.get_moon_position(
    c_int(date_structure['y']),
    c_int(date_structure['m']),
    c_int(date_structure['d']),
    c_int(date_structure['hh']),
    c_int(date_structure['mm']),
    c_int(date_structure['ss']),
    bulletinb_file_init_time
)

print("moon:", moon_position)

eocfi_sat.get_sun_position.restype = ndpointer(dtype=c_double, shape=(3,))
sun_position = eocfi_sat.get_sun_position(
    c_int(date_structure['y']),
    c_int(date_structure['m']),
    c_int(date_structure['d']),
    c_int(date_structure['hh']),
    c_int(date_structure['mm']),
    c_int(date_structure['ss']),
    bulletinb_file_init_time
)

print("sun :", sun_position)

eocfi_sat.get_satellite_position.restype = ndpointer(dtype=c_double, shape=(3,))
sat_position = eocfi_sat.get_satellite_position(
    c_long(sat_id),
    c_int(date_structure['y']),
    c_int(date_structure['m']),
    c_int(date_structure['d']),
    c_int(date_structure['hh']),
    c_int(date_structure['mm']),
    c_int(date_structure['ss']),
    bulletinb_file_init_time,
    make_clist(orbit_files),
    c_long(sat_n_files)
)
print(sat, ": ", sat_position)

transformer = pyproj.Transformer.from_crs(
    {"proj": 'geocent', "ellps": 'WGS84', "datum": 'WGS84'},
    {"proj": 'latlong', "ellps": 'WGS84', "datum": 'WGS84'},
    )
lat, lon, hhh = transformer.transform(sat_position[0],sat_position[1],sat_position[2], radians=False)
print("Geocentric: ", 360+lat, lon, hhh)
