from argparse import Namespace
from typing import Optional, TypedDict

from remap_badblocks.src.devices.device_config import DeviceConfig
from remap_badblocks.src.devices.devices_config import DevicesConfig


class SetArgs(TypedDict):
    device_id: Optional[int]
    device_name: Optional[str]
    enable: Optional[bool]
    rename: Optional[str]


def get_device_from_args(args: SetArgs, dc: DevicesConfig) -> DeviceConfig:
    if args["device_id"] is None:
        if args["device_name"] is not None:
            return dc.get_device(name=args["device_name"])
        else:
            raise ValueError(
                "Either --id or --name must be provided to set a device in the database."
            )

    return dc.get_device(id=args["device_id"])


def parse_args(args: Namespace) -> SetArgs:
    return {
        "device_id": args.id,
        "device_name": args.name,
        "enable": args.enable,
        "rename": args.rename,
    }


def set(dc: DevicesConfig, _args: Namespace) -> None:
    """
    Set the configuration of a device from the database.
    """
    args = parse_args(_args)

    device: DeviceConfig = get_device_from_args(args, dc)

    if args["enable"] is not None:
        dc.update_device(
            id=device.id,
            enabled=args["enable"],
        )

    if args["rename"] is not None:
        dc.update_device(
            id=device.id,
            name=args["rename"],
        )

    print("Device config updated.")
