"""
Command to create media symlink for rldjango.common app
"""

import os

from django.core.management.base import NoArgsCommand
from django.conf import settings

from rldjango import common

def create_dir(location):
    """
    Creates location if doesnt exists.
    """
    if not os.path.exists(location):
        print "Creating", location
        os.mkdir(location)

def create_symlink(source, target):
    """
    Creates symlink if doesnt exists.
    """
    if not os.path.exists(target):
        print "Creating symlink", source, target
        os.symlink(source, target)

def tree_editor_media():
    """
    Symlink tree_editor media.
    """
    create_dir(os.path.join(get_media_root(), 'common'))
    source = os.path.join(get_common_root(), 'media', 'tree_editor')
    target = os.path.join(get_media_root(), 'common', 'tree_editor')
    create_symlink(source, target)

def html_field_media():
    """
    Symlink html_field media.
    """
    create_dir(os.path.join(get_media_root(), 'common'))
    source = os.path.join(get_common_root(), 'rsrc')
    target = os.path.join(get_media_root(), 'common', 'rsrc')
    create_symlink(source, target)

def get_common_root():
    """
    Returns rldjango.common path
    """
    return os.path.join(os.path.realpath(common.__path__[0]))
    
def get_media_root():
    """
    Returns settings.MEDIA_ROOT
    """
    return settings.MEDIA_ROOT

   
class Command(NoArgsCommand):
    """
    Adds sync_media command to manage.py
    TODO: support for multiple components
    """
    def handle_noargs(self, **options):
        """
        Prepares media for common components
        """
        tree_editor_media()        
        html_field_media()
