#!/usr/bin/env python
# -*- coding: utf-8 -*-

from vm import Vm
from optparse import OptionParser
from operator import attrgetter


if __name__ == '__main__':

    parser = OptionParser('%s [options] [name1 [name2 ...]]' % __file__)
    parser.add_option('-l', '--long', dest='long', action='store_true',
                      default=False,
                      help='List in long format.')
    parser.add_option('-r', '--running', dest='run', action='store_true',
                      default=False,
                      help='List only running VMs.')
    parser.add_option('-s', '--sort', dest='key', action='append',
                      default=[],
                      help='key to sort by. User can specify many times.'
                      " Value shoud be 'os' or 'core' or 'memory' or 'uuid' or"
                      " 'ssh_port'")

    (options, args,) = parser.parse_args()

    if args:
        vms = map(Vm, args)
    else:
        vms = map(Vm, Vm.list_vms())

    if options.run:
        vms = filter(attrgetter('is_running'), vms)

    order_keys = options.key + ['os', 'name', 'uuid']
    vms = sorted(vms, key=attrgetter(*order_keys))

    statuses = ['run'] + ['*' if vm.is_running else '' for vm in vms]
    names = ['Name'] + [vm.name for vm in vms]
    cores = ['Core'] + [str(vm.core) for vm in vms]
    memories = ['Mem'] + [vm.memory for vm in vms]
    oses = ['OS'] + [vm.os for vm in vms]
    uuids = ['UUID'] + [vm.uuid for vm in vms]
    ssh_ports = ['SSH Host Port'] + [str(vm.ssh_port) for vm in vms]

    if options.long:
        format = '%%-%ds %%-%ds %%-%ds %%-%ds %%-%ds %%-%ds %%-%ds' % (
            max(map(len, statuses)),
            max(map(len, names)),
            max(map(len, oses)),
            max(map(len, cores)),
            max(map(len, memories)),
            max(map(len, uuids)),
            max(map(len, ssh_ports)),
        )

        for status, name, os, core, memory, uuid, port, in zip(
                statuses, names, oses, cores, memories, uuids, ssh_ports,):
            print(format % (status, name, os, core, memory, uuid, port,))

    else:
        format = '%%-%ds %%-%ds' % (
            max(map(len, statuses)),
            max(map(len, names)),
        )

        for status, name in zip(statuses, names,):
            print(format % (status, name,))
