import requests
import yaml
import os

url = 'http://10.32.16.55/MainWebFrom.aspx'

yaml_station_ID = 'not found in YAML'
yaml_op = 'not found in YAML'
yaml_firmware_version = 'not found in YAML'


def mes_add(sn, test_result, uut_start, uut_stop, software_version):
    read_default_values()

    formatted_string = (f'cmd=ADD&sn={sn}'
                        f'&op={yaml_op}&'
                        f'Fixture_ID=&'  # Fixture ID currently unused, but should still send empty value
                        f'Station_ID={yaml_station_ID}&'  # VAP T060 MMI T070 BT T080
                        f'testdata=test_result={test_result}$'  # PASS or FAIL
                        f'unit_sn={sn}$'
                        f'uut_start={uut_start}$'
                        f'uut_stop={uut_stop}$'
                        f'software_version={software_version}$'
                        f'station_id={yaml_station_ID}')

    try:
        requests.post(url, data=formatted_string, headers={'Content-Type': 'application/x-www-form-urlencoded'}, timeout=5)
    except Exception as e:
        print(e)

    return formatted_string


def read_default_values():
    global yaml_station_ID, yaml_op, yaml_firmware_version

    if not os.path.isfile("MES_default.yaml"):
        print("MES_default.yaml not found in same directory as MMI executable.")
        yaml_station_ID = 'YAML file not found'
        yaml_op = 'YAML file not found'
        return

    with open("MES_default.yaml", "r") as f:
        data = yaml.safe_load(f)

    yaml_station_ID = data['station_id']
    yaml_op = data['op']
    yaml_firmware_version = data['firmware_version']


def get_firmware_version():
    read_default_values()
    return yaml_firmware_version

