import asyncio
import json
import os

from server.apis import appData
from server.data.definitions import ECP_WORK_FILES_DIR, Paths
from server.utils.VersionControl import VersionControl, UNKNOWN_VERSION

PATH_ECP_WORK_DIR = f"{os.environ.get(ECP_WORK_FILES_DIR, Paths.DEFAULT_ECP_WORK_DIR.value)}"
PATH_ECP_CONFIGS_DIR = f"{PATH_ECP_WORK_DIR}/{Paths.ECP_CONFIGS_SUBDIR.value}"


async def setup_app_data():
    """Sets up the application data."""
    # ---------- SERIAL

    with open(os.path.join(PATH_ECP_CONFIGS_DIR, "config.json")) as file:
        config = json.load(file)

    # Copied from OCPPConfiguration.py in ECP
    # TODO: Find a common source of this information with ECP

    device = config.get("Device")
    serial = device.get("Serial")
    CB_MODEL = "{:0>5}.{}{}".format(serial.get("Art"), serial.get("MajRev"), serial.get("MinRev"))
    CB_SERIAL = "{:0>2}{:0>2}{:0>4}".format(serial.get("Year"), serial.get("Batch"), serial.get("Serial"))
    appData.serial = "{} {}".format(CB_SERIAL, CB_MODEL)

    role = device.get("Role")
    appData.role = role

    # ---------- DEVICE_ID

    process = await asyncio.create_subprocess_shell(
        'grep /etc/motd -Poe "(?<=ID:     )(/d|\w){10}"', stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
    )
    stdout, stderr = await process.communicate()

    appData.deviceId = stdout.decode().strip()

    # ---------- MSI_VERSION

    appData.msiiVersion = VersionControl.readMsiVersion()

    # ---------- RAUC VERSIONS

    # In docker the rauc environment doesn't exist
    if not os.path.exists("/.dockerenv"):
        osVersion, rescueOsVersion = await VersionControl.getRaucVersions()
        if osVersion == UNKNOWN_VERSION:
            osVersion = VersionControl.readOsRelease()
    else:
        osVersion = "2.3.69"
        rescueOsVersion = "2.3.69"

    if osVersion and rescueOsVersion:
        appData.osReleaseVersion = osVersion
        appData.rescueOsVersion = rescueOsVersion

    # ---------- ECP_VERSION

    appData.ecpVersion = VersionControl.getVersion()
