from argparse import Namespace
from typing import Iterable, Optional, TypedDict

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


class GetArgs(TypedDict):
    device_id: Optional[int]
    device_name: Optional[str]
    all: bool


def parse_args(args: Namespace) -> GetArgs:
    return {
        "device_id": args.id,
        "device_name": args.name,
        "all": args.all,
    }


def get_devices_to_print(args: GetArgs, dc: DevicesConfig) -> Iterable[DeviceConfig]:
    if args["device_id"] is not None:
        return [dc.get_device(id=args["device_id"])]
    elif args["device_name"] is not None:
        return [dc.get_device(name=args["device_name"])]
    elif args["all"]:
        return dc.get_devices()
    else:
        return filter(lambda d: d.enabled, dc.get_devices())


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

    for device in get_devices_to_print(args, dc):
        print(str(device))
