#!/usr/bin/env python
import os
import sys
import argparse
import errno
import logging
#from django.template import Context, Template
#from django.conf import settings
#settings.configure()


"""
    This is the vagabond command line utility
"""

# This is the version number
API_VERSION=0.1

# Set up Module Logging
# TODO:  Read this https://docs.python.org/2/howto/logging-cookbook.html
L = logging.getLogger(__name__)
L.setLevel(logging.DEBUG)

ch = logging.StreamHandler()
ch.setLevel(logging.INFO)

L.addHandler(ch)

def getArgs():
    parser = argparse.ArgumentParser(description="Build and Manage a VirtualBox machine using python")
    subparser = parser.add_subparsers(help="Sub processor help", dest="subparser_name")

    # Need to implement these
    init_parser = subparser.add_parser('init', help="Start a Vagabond Project")
    init_parser.add_argument('name', help="The name of the project")
    init_parser.add_argument('-f', '--force', action="store_true", help="Overwrite existing Vagabond.py file")

    # Neither of these are current used       
    destroy_parser = subparser.add_parser('up', help="Bring the machine up")
    
    list_parser = subparser.add_parser('list', help="list options")
    list_parser.add_argument('--ostypes', action="store_true", help="Print a list of valid ostypes and exit")
    return parser.parse_args()

def up(V):
    """
        Creating the VM from an ISO image
        http://www.perkin.org.uk/posts/create-virtualbox-vm-from-the-command-line.html
    """
    # Check for Vagabond.py file
    _file = os.path.join(os.getcwd(), "Vagabond.py")
    if not os.path.isfile(_file):
        L.error("No Vagabond.py file found.  Is this is this a vagabond project?")
        sys.exit(0)
       
    config = V.config
    hostname = config.get('hostname', 'vagabond')
  
    count = 0
    for media, value in config['media'].items():    
        if value:
            media_type = media
            media_val = value
            count = count + 1
            
    if count > 1:
        L.info("You may only define one media type in %s"%config['media'].keys())
        sys.exit(0)
    
    
def init(args):
    """
        Initialize a project by:
        1)  Create a direction (args.name)
        2)  Use UPDATE_ME template to create initial Vagabond.py file
    """
    # The path to create the Vagabond.py file
    vfile = os.path.join(args.name, "Vagabond.py")
    try:
        os.mkdir(args.name)
    except OSError as e:
        if errno.errorcode[e.errno] == 'EEXIST': #File Exists:  https://docs.python.org/2/library/errno.html
            # Check for Vagabond file to confirm it is a vagabond project
            if os.path.isfile(vfile) and args.force:
                pass
            elif os.path.isfile(vfile) and not args.force:
                L.error("There is already a vagabond project named %s, please choose another name"%args.name)
                L.error("If you would like to force a reinitialize then pass --force")
                sys.exit(0)
            else:
                L.error("There is already a directory named %s"%args.name)
                sys.exit(0)
        else:        
            raise
  
    # Now we need to use a templating system to copy our initial Vagabond.py file into the project directory 
    # TODO Make sure this works when installed as a python package
    #template_dir = os.path.normpath(
    #    os.path.join(
    #        os.path.dirname(os.path.abspath(__file__)),
    #        "../vagabond/templates"
    #    )
    #)
    #t=Template(open('%s/Vagabond.py'%template_dir, 'r').read())
    #c = Context({'version':API_VERSION})
    from vagabond.templates import VagabondTemplate
    VagabondTemplate.render({'version':API_VERSION})
    with open(vfile, 'w') as f:
        f.write( VagabondTemplate.render({'version':API_VERSION}) )
        #f.write(t.render(c))
        

def readVagabond():
    # Check for Vagabond file in local directory
    vfile = os.path.join(os.getcwd(), "Vagabond.py")
    if not os.path.isfile(vfile):
        raise IOError("You must have a Vagabond file in your current directory")

    # Add current directory to sys path...
    # so that when we load the Vagabond module it loads the users module
    sys.path.insert(0, os.getcwd())

    #TODO Need to do a verify/check on the imported Vagabond file.

    return Vagabond


#if __name__ == '__main__':
if __name__ == '__main__' and __package__ is None:
    from os import sys, path
    sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
    from vagabond.vm import VM

    args = getArgs()
    if args.subparser_name == 'init':
        init(args)
    elif args.subparser_name == 'list':
        if args.ostypes:
            VM.show_valid_os_types()
    elif args.subparser_name == 'up':
        # Read the Vagrant file in the current directory
        vm = VM( options=readVagabond() )
        vm.up()
        
        
