#!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id: setup.py 9438 2015-09-25 07:43:20Z Eric $
#
# Copyright (c) 2015 Nuwa Information Co., Ltd, All Rights Reserved.
#
# Licensed under the Proprietary License,
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at our web site.
#
# See the License for the specific language governing permissions and
# limitations under the License.
#
# $Author: Eric $ (last)
# $Date: 2015-09-25 15:43:20 +0800 (Fri, 25 Sep 2015) $
# $Revision: 9438 $

import shutil

from django.core.management.base import BaseCommand

class Command(BaseCommand):
    
    help = 'Copy default registration templates to project or appointed app'
    args = '[app]'
    
    # Validation is called explicitly each time the server is reloaded.
    requires_model_validation = False
    
    def handle(self, app='', *args, **options):
        
        import os
        import pkg_resources
        from django.conf import settings
        
        if hasattr(settings, 'BASE_DIR'):
            projectDir = settings.BASE_DIR
        else:
            projectDir = os.path.abspath(os.path.curdir)
        
        iunoDir = pkg_resources.get_distribution('Iuno').location
        memberTemplatesDir = os.path.join(iunoDir, 'Iuno', 'member',
                                          'templates', 'member')
    
        if app:
            pTemplatesDir = os.path.join(projectDir, app, 'templates')
        else:
            pTemplatesDir = os.path.join(projectDir, 'templates')
            
        isTemplatesDirExist = os.path.exists(pTemplatesDir)
        
        if not isTemplatesDirExist:
            os.makedirs(pTemplatesDir)
        os.makedirs(os.path.join(pTemplatesDir, 'member'))
        mTemplatesDir = os.path.join(pTemplatesDir, 'member')
        
        # copy.
        for file in os.listdir(memberTemplatesDir):
            
            if file.startswith("_"):

                shutil.copy(os.path.join(memberTemplatesDir, file),
                            mTemplatesDir)
        # rename.        
        for file in os.listdir(mTemplatesDir):
            
            if file.startswith("_"):
                
                os.rename(os.path.join(mTemplatesDir, file),
                          os.path.join(mTemplatesDir, file[1:]))
        
        from Iuppiter.Util import colored, cprint
        
        print("Iuno.member templates are successfully installed in %s !!!"
              % (colored(mTemplatesDir, 'yellow', attrs=['bold'])))
