from uncloud.common.parser import BaseParser
from uncloud.cli.helper import make_request, get_otp_parser


class VMParser(BaseParser):
    def __init__(self):
        super().__init__('vm')

    def start(self, **args):
        p = self.subparser.add_parser('start', parents=[get_otp_parser()], **args)
        p.add_argument('--vm-name', required=True)

    def stop(self, **args):
        p = self.subparser.add_parser('stop', parents=[get_otp_parser()], **args)
        p.add_argument('--vm-name', required=True)

    def status(self, **args):
        p = self.subparser.add_parser('status', parents=[get_otp_parser()], **args)
        p.add_argument('--vm-name', required=True)

    def delete(self, **args):
        p = self.subparser.add_parser('delete', parents=[get_otp_parser()], **args)
        p.add_argument('--vm-name', required=True)

    def migrate(self, **args):
        p = self.subparser.add_parser('migrate', parents=[get_otp_parser()], **args)
        p.add_argument('--vm-name', required=True)
        p.add_argument('--destination', required=True)

    def create(self, **args):
        p = self.subparser.add_parser('create', parents=[get_otp_parser()], **args)
        p.add_argument('--cpu', required=True)
        p.add_argument('--ram', required=True)
        p.add_argument('--os-ssd', required=True)
        p.add_argument('--hdd', action='append', default=list())
        p.add_argument('--image', required=True)
        p.add_argument('--network', action='append', default=[])
        p.add_argument('--vm-name', required=True)


parser = VMParser()
arg_parser = parser.arg_parser


def main(**kwargs):
    subcommand = kwargs.pop('vm_subcommand')
    if not subcommand:
        arg_parser.print_help()
    else:
        data = kwargs
        endpoint = subcommand
        if subcommand in ['start', 'stop', 'delete']:
            endpoint = 'action'
            data['action'] = subcommand
        elif subcommand == 'create':
            kwargs['specs'] = {
                'cpu': kwargs.pop('cpu'),
                'ram': kwargs.pop('ram'),
                'os-ssd': kwargs.pop('os_ssd'),
                'hdd': kwargs.pop('hdd')
            }
        make_request('vm', endpoint, data=data)
