import time
import pandas as pd
import pyvisa
import time


file1 = "VOZNJA_LJUBLJANA_KOPER.AGS"
file2 = "VOZNJA_LJUBLJANA_MARIBOR.AGS"
file3 = "STATICNO_KRIM.AGS"
file4 = "STATICNO_LJUBLJANSKI_GRAD.AGS"

simulation_file = [["STATIČNO #1","STATICNO_KRIM.AGS"],["STATIČNO #2","STATICNO_LJUBLJANSKI_GRAD.AGS"],["DINAMIČNO #1","VOZNJA_LJUBLJANA_KOPER.AGS"],["DINAMIČNO #2","VOZNJA_LJUBLJANA_MARIBOR.AGS"]]


def load_scenario(sg,file):
    """
    Loads a GNSS scenario file into the signal generator.

    Parameters:
    sg (pyvisa.resources.Resource): The signal generator resource object.
    file_name (str): The name of the scenario file to load.
    """
    try:
        
        sg.write(f"SOURce:RADio:GNSS:SCENario '{file}'")


    except pyvisa.VisaIOError as e:
        print(f"Error loading scenario: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

def scenario_off(sg):
    """
    [:SOURce]:RADio:GNSS[:BBG][:STATe] 1|0|ON|OFF
    [:SOURce]:RADio:GNSS[:BBG]:SCENario:RESTart
    """
    try:
        sg.write(':SOURce:RADio:GNSS OFF')
        #print("Scenario off")
    except pyvisa.VisaIOError as e:
        print(f"Error restarting scenario: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
    time.sleep(0.1)

def scenario_on(sg):
    """ 
    [:SOURce]:RADio:GNSS[:BBG][:STATe] 1|0|ON|OFF
    """
    try:
        sg.write(':SOURce:RADio:GNSS ON')
        #print("Scenario on")
    except pyvisa.VisaIOError as e:
        print(f"Error restarting scenario: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        time.sleep(0.01)

#### ZACETEK PROGRAMSKE KODE ####
print("LSO - GNSS simulacija - L1 - 11.06.2024\n")
print("Omogočeni scenariji:")
for id, scenarij in enumerate(simulation_file):
    print("[" + str(id+1) + "]: " + scenarij[0])


izbira = 1
while(izbira != 0):
    izbira = input("Izbira scenarija [0 - izhod]: ")
    if(izbira == "0"):
        None
    elif(int(izbira) not in [1,2,3,4]):
        print("Neveljavna izbira!\n")
    else:
        rm = pyvisa.ResourceManager()
        sg = rm.open_resource('TCPIP0::1.1.1.2::inst0::INSTR')
        scenario_off(sg)
        time.sleep(0.1)
        sg.write(':SOURce:RADio:GNSS:SCEN:SOUR USER')
        time.sleep(0.1)
        sg.write(':SOURce:RADio:GNSS:SATP RANG')
        load_scenario(sg,simulation_file[int(izbira)-1][1])
        time.sleep(0.1)
        scenario_on(sg)
        time.sleep(0.1)
        sg.write(':SOURce:RADio:GNSS:SCENario:STIMe:OFFset 0')
        time.sleep(0.1)
        sg.write(':OUTPut:STATe ON')
        sg.close()
        print("Scenarij nastavljen - OK\n")