import warnings
import os
import json

from UniTAP.dev.ports.modules.pdc.pdo import Pdo
from UniTAP.dev.ports.modules.pdc.pdo_utils import get_pdo_value
from UniTAP.dev.ports.modules.pdc.pdo_types import *
from UniTAP.dev.ports.modules.pdc.pdo_private_types import PdoUnion


def support_or_not(value) -> str:
    return "Yes" if bool(value) else "No"


def save_pdo(path: str, pdo_list: list, source: bool):
    filename, file_extension = os.path.splitext(path)
    if file_extension.find('.txt') != -1:
        file = open(path, 'w')
        file.write("TSI_USBC_PWR_LOCAL_SOURCE_PDO\n" if source else "TSI_USBC_PWR_LOCAL_SINK_PDO\n")
        file.write("1\n")
        file.write(str(len(pdo_list) * 4))
        for pdo in pdo_list:
            file.write(str(get_pdo_value(pdo.get_pdo_object())))
        file.close()
    elif file_extension.find('.json') != -1:
        values = {}
        for index, pdo in enumerate(pdo_list):
            values.update({f"EPR{index}": get_pdo_value(pdo.get_pdo_object())})
        with open(path, "w") as outfile:
            json.dump(values, outfile)
    else:
        warnings.warn(f"Unsupported file format: {file_extension}. "
                      f"Please, select file format from available variants: 'txt', 'json'")


def load_pdo(path: str, source: bool) -> list:
    if os.path.exists(path):
        raise ValueError(f"Incorrect path {path} to file. Path does not exist.")
    filename, file_extension = os.path.splitext(path)
    pdo_list = []
    if file_extension.find('.txt') != -1:
        file = open(path, 'r')
        data = file.read().split("\n")
        for index, line in enumerate(data):
            if index >= 3:
                fill_list(int(line), pdo_list, source)
        file.close()
    elif file_extension.find('.json') != -1:
        with open(path, "r", encoding='utf-8') as read_file:
            data = json.load(read_file)
        keys = list(data.keys())
        for index, key in enumerate(keys):
            fill_list(int(data.get(key)), pdo_list, source)
    else:
        raise ValueError(f"Unsupported file format: {file_extension}. "
                         f"Please, select file format from available variants: 'txt', 'json'")
    return pdo_list


def fill_list(data, pdo_list, source):
    pdo_data = PdoUnion(data)
    pdo_type = PdoTypeEnum(pdo_data.brief_info.pdo_type)
    if pdo_type == PdoTypeEnum.Fixed:
        pdo_list.append(Pdo(pdo=FixedPdoSource(pdo_data.fixed_pdo_source) if source else
                            FixedPdoSink(pdo_data.fixed_pdo_sink),
                            side=PdoSide.Source if source else PdoSide.Sink))
    elif pdo_type == PdoTypeEnum.Battery:
        pdo_list.append(Pdo(pdo=BatteryPdo(pdo_data.battery_pdo),
                            side=PdoSide.Source if source else PdoSide.Sink))
    elif pdo_type == PdoTypeEnum.Variable:
        pdo_list.append(Pdo(pdo=VariablePdo(pdo_data.variable_pdo),
                            side=PdoSide.Source if source else PdoSide.Sink))
