# -*- coding: utf-8 -*-
import os
import sys
from django.core.management.base import BaseCommand
from optparse import make_option
from django.conf import settings
from django_addons import get_meta

class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('--enable', '-e', default=None, dest='addon_to_enable',
            help='Enable a addon'),
        make_option('--disable', '-d', default=None, dest='addon_to_disable',
            help='Disable a addon'),
    )
    help = "List, enable or disable addons."

    requires_model_validation = False
    can_import_settings = False

    def handle(self, *args, **options):
        def save():
            print "Saving to:", settings.ADDONS_DISABLED_CONF
            fh = open( settings.ADDONS_DISABLED_CONF, "w")
            fh.write("# This file is automatically generated by ./manage.py addons\n")
            fh.write("# To enable an addon use: ./manage.py addons -e ADDON_NAME\n")
            fh.write("# To disable an addon use: ./manage.py addons -d ADDON_NAME\n")
            fh.write("ADDONS_DISABLED = [ %s ]\n" % ", ".join("'%s'" % x for x in settings.ADDONS_DISABLED))
            fh.close()

        def addon_enable(addon):
            if not addon:
                return
            if addon in settings.ADDONS_DISABLED:
                print "Enabling addon: %s" % addon
                settings.ADDONS_DISABLED.remove(addon)
                save()
            if not addon in settings.ADDONS:
                settings.ADDONS.append(addon)

        def addon_disable(addon):
            if not addon:
                return
            if addon in settings.ADDONS:
                if addon not in settings.ADDONS_DISABLED:
                    print "Disabling addon: %s" % addon
                    settings.ADDONS.remove(addon)
                    settings.ADDONS_DISABLED.append(addon)
                    save()
                    return True

        # Enable addon if we have to
        addon_enable(options.get("addon_to_enable"))
        # Disable addon if we have to
        addon_disable(options.get("addon_to_disable"))

        # Otherwise display list of addon
        print "Available addons:"
        for addon in settings.ADDONS:


            print " * %s" % addon,
            meta = get_meta(addon)
            if meta:
                print "- %s" % meta.title,
            print

        for addon in settings.ADDONS_DISABLED:
            print " * %s (disabled)" % addon
