#!/usr/bin/env python
# encoding: utf-8

import os
import json
import asyncio
import time
from transitions import Machine
from rt_hat import PHY as RT_HAT_PHY

CONFIG_FILE = '/usr/share/InnoRoute/INR_PHY_config.json'
TEMP_FILE = '/usr/share/InnoRoute/INR_PHY_config_temp.json'
BLOCKED_FILE = '/usr/share/InnoRoute/blocked.json'
phy_link_status = [1, 1]
phy_linkspeed = [2, 2]

def int2phy_speed(speed):
    if speed == 0:
        return "10"
    if speed == 1:
        return "100"
    if speed == 2:
        return "1000"

while 1:
  time.sleep(3)
  (phy_link_status[0], phy_linkspeed[0]) = RT_HAT_PHY.get_link_status(0)
  (phy_link_status[1], phy_linkspeed[1]) = RT_HAT_PHY.get_link_status(1)
  if (phy_link_status[0]==1):
    RT_HAT_PHY.set_FPGA(phy_linkspeed[0],0)
  if (phy_link_status[1]==1):
    RT_HAT_PHY.set_FPGA(phy_linkspeed[1],1)
  try:
    with open(CONFIG_FILE, 'r') as file:
        data = json.load(file)
        data[f"PHY0_state"] = str(int2phy_speed(phy_linkspeed[0]))
        data[f"PHY2_state"] = str(int2phy_speed(phy_linkspeed[1]))
        if phy_link_status[0]==0:
          data[f"PHY0_state"] = "down"
        if phy_link_status[1]==0:
          data[f"PHY2_state"] = "down"
    with open(CONFIG_FILE, 'w') as file:
        json.dump(data, file, indent=4)
  except Exception as e:
    print(f"Error applying configuration: {e}")

