"""
Project actions
"""
import subprocess
from django.core.management import call_command
import os
from . import BaseCommand
from snelis.management import utils


class Command(BaseCommand):

    template_path = os.path.join(os.path.dirname(os.path.realpath(utils.__file__)), 'templates')

    def handle(self):
        """
        Create project structure
            [*] django-admin.py startproject location --template=url
            [ ] subprocess.call(["virtualenv", "--no-site-packages", "venv (--venv-name) "])

        """
        if self.args('create', 'project'):
            self.create_project()

    def create_project(self):

        # Define some values we use to setup the application
        project_path = os.path.abspath(self.value('path'))
        project_name = os.path.basename(project_path)
        template_path = os.path.join(self.template_path, 'startproject')
        venv_path = os.path.join(project_path, self.option('venv-name'))
        box_name = self.option('box-name')
        box_url = self.option('box-url')

        # See if the user wants another template
        if self.option('template'):
            template_path = self.option('template')

        print "Creating project with name: {0}".format(project_name)

        # Here we call django to actually create the project, with our own template
        options = self.args_context()
        options.update(template=template_path,
                       files=('Vagrantfile',),
                       )
        call_command('startproject', project_name, **options)

        if not self.option('no-virtualenv'):
            # Create the virtualenv
            if os.path.exists(venv_path):
                print 'Virtualenv at {0} already exists, skipping'
            else:
                subprocess.call(["virtualenv", venv_path, "--no-site-packages"])

        # Create the vagrant file
        # vagrant init precise64
        # if not self.option('no-vagrant'):
            #subprocess.call(["vagrant", "init", box_name, box_url])