#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010-2012 Código Sur Sociedad Civil
# All rights reserved.
#
# This file is part of Cyclope.
#
# Cyclope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Cyclope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import sys
from optparse import make_option

import django
from django.core.management.base import CommandError
from django.core.management.templates import TemplateCommand
from django.utils.crypto import get_random_string
from django.utils.importlib import import_module

import cyclope

class Command(TemplateCommand):
    help = ("Creates a Cyclope project directory structure for the given "
            "project name in the current directory.")

    template = os.path.join(cyclope.__path__[0], "conf", "project_template")

    option_list = TemplateCommand.option_list + (
        make_option('--directory', action='store', dest='directory',
            default=".", help='Destination directory '
                'where the project will be created.'),
    )

    def handle(self, project_name=None, target=None, *args, **options):
        if project_name is None:
            raise CommandError("you must provide a project name")

        # Check that the project_name cannot be imported.
        try:
            import_module(project_name)
        except ImportError:
            pass
        else:
            raise CommandError("%r conflicts with the name of an existing "
                               "Python module and cannot be used as a "
                               "project name. Please try another name." %
                               project_name)

        # Create a random SECRET_KEY hash to put it in the main settings.
        chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
        options['secret_key'] = get_random_string(50, chars)

        if not options.get("template", None):
            options["template"] = self.template

        super(Command, self).handle('project', project_name, target, **options)

        # Create media
        import markitup
        import admin_tools
        import filebrowser
        import mptt_tree_editor
        media = (
            ("admin", os.path.join(django.__path__[0], "contrib", "admin", "static", "admin")),
            ("markitup", os.path.join(markitup.__path__[0], "static", "markitup")),
            ("admin_tools", os.path.join(admin_tools.__path__[0], "media", "admin_tools")),
            ("filebrowser", os.path.join(filebrowser.__path__[0], "static", "filebrowser")),
            ("cyclope", os.path.join(cyclope.__path__[0], "media")),
            ("mptt_tree_editor", os.path.join(mptt_tree_editor.__path__[0], "static", "mptt_tree_editor")),
        )

        directory = options.get("directory")
        top_dir = os.path.join(directory, project_name)
        media_dir = os.path.join(top_dir, "media")
        os.mkdir(media_dir)
        for name, path in media:
            os.symlink(path, os.path.join(media_dir, name))

        # Create upload directory
        os.mkdir(os.path.join(media_dir, "uploads"))

        # FIXME: this should not be here
        # Create db
        os.mkdir(os.path.join(top_dir, "db"))
        
        if options['verbosity'] != "0":
            print u"\nProject %s created successfully!\n" % project_name
            sync_msg = u"" \
                u"Now you must:\n\n" \
                u"    1) cd to %s\n" \
                u"    2) run 'python manage.py syncdb' to create database\n" \
                u"    3) run 'python manage.py migrate' to load cyclope db migrations\n" \
                u"    4] run 'python manage.py loaddata default_groups.json' to load\n" \
                u"       cyclope default group permissions (Optional)\n"  % top_dir
            print sync_msg

if __name__ == "__main__":
    cmnd = Command()
    if len(sys.argv) == 1:
        cmnd.print_help("startcyclopeproject", "")
    else:
        sys.argv.insert(0, "") # Hack run_from_argv
        cmnd.run_from_argv(sys.argv)
