import json
import logging
import sys
from typing import Callable, Any

from app import app
from app.cli import _SubparserType, BaseCliHandler
from app.lists import lists
from app.models.base import Pool


def dump(list_f: Callable[[Pool], Any]) -> None:
    json.dump(list_f(Pool.query.first()), sys.stdout, indent=2)


class ListCliHandler(BaseCliHandler):
    @classmethod
    def add_subparser_to(cls, subparsers: _SubparserType) -> None:
        parser = subparsers.add_parser("list", help="list operations")
        parser.add_argument("--dump", choices=sorted(lists.keys()),
                            help="dump a list in JSON format")
        parser.set_defaults(cls=cls)

    def run(self) -> None:
        with app.app_context():
            if self.args.dump:
                dump(lists[self.args.dump])
            else:
                logging.error("No action requested")
