#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import urllib2
import re
import getopt
import sys
from subprocess import Popen, PIPE

'''
{{project}}/
   src/
       app/ – all of the files to be used in production
           content/
               css/ – css files
               images/ – image files
               fonts/ - font files
               partials/ – angular view partials (partial html templates)
           index.html – app layout file (the main html template file of the app)
           favicon.ico
           robots.txt
           js/ – javascript files
               app.js – application
               controllers/ – application controllers
               directives/ – application directives
               filters/ – custom angular filters
               services/ – custom angular services
           lib/ – angular and 3rd party javascript libraries
       config/ – config files for running unit tests with Testacular/Karma
       test/ – test source files and libraries
           unit/ - unit test
           behaiviors/ - specifications
   res/scripts/ – handy shell/js/ruby scripts (run unit tests and dev server)
'''

gitResourceUri = 'https://raw.github.com/skat-delayed/projectTemplate/master/'
angularVersion = '1.2.1'

def downloadFile(fileUrl, destination):
    fileName = fileUrl.split('/')[-1]
    fullFilePath = os.path.join(destination, fileName)
    u = urllib2.urlopen(fileUrl)
    f = open(fullFilePath, 'wb')
    meta = u.info()
    print(meta)
    file_size = int(meta.getheaders("Content-Length")[0])
    print "Downloading: %s Bytes: %s" % (fileName, file_size)

    file_size_dl = 0
    block_sz = 8192
    while True:
        buffer = u.read(block_sz)
        if not buffer:
            break
        file_size_dl += len(buffer)
        f.write(buffer)
        status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
        status = status + chr(8)*(len(status)+1)
        print status,
    f.close()

def createStructure(projectDir):
    directories = [ 'src\\app\\content\\css',
                'src\\app\\content\\images',
                'src\\app\\content\\fonts',
                'src\\app\\content\\partials',
                'src\\app\\js\\controllers',
                'src\\app\\js\\directives',
                'src\\app\\js\\filters',
                'src\\app\\js\\services',
                'src\\app\\lib',
                'res\\config',
                'res\\scripts',
                'src\\test\\unit',
                'src\\test\\e2e',
                'src\\test\\lib',
                'doc',
                'res'
                ]

    for directory in directories:
        currentDir = os.path.join(projectDir, directory)

        if not os.path.exists(currentDir):
            os.makedirs(currentDir)
#            open(os.path.join(currentDir, '.gitkeep'), 'a').close()

def gitInitAndCommit(projectDir):
    Popen('git init', cwd=projectDir, stdout=PIPE).communicate()
    Popen('git add .', cwd=projectDir, stdout=PIPE).communicate()
    Popen('git commit -m \"S: initial commit \"', cwd=projectDir, stdout=PIPE).communicate()

def fillWithLife(projectDir, projectName):
    with open(os.path.join(projectDir, 'readme.md'), 'a') as readMe:
        readMe.write('##' + projectName +'\n')

    with open(os.path.join(projectDir, '.gitattributes'), 'a') as readMe:
        readMe.write('# Disable LF normalization for all files\n* -text')

    # ----- js resources
    downloadFile(   'http://code.angularjs.org/' + angularVersion + '/angular.js',
                    os.path.join(projectDir, 'src\\app\\lib\\'))
    downloadFile(   'http://code.angularjs.org/' + angularVersion + '/angular-route.js',
                    os.path.join(projectDir, 'src\\app\\lib\\'))
    downloadFile(   'http://code.angularjs.org/' + angularVersion + '/angular-scenario.js',
                    os.path.join(projectDir, 'src\\test\\lib\\'))
    downloadFile(   'http://code.angularjs.org/' + angularVersion + '/angular-mocks.js',
                    os.path.join(projectDir, 'src\\test\\lib\\'))
    downloadFile(   'http://code.angularjs.org/' + angularVersion + '/version.txt',
                    os.path.join(projectDir, 'src\\test\\lib\\'))
    downloadFile(   'https://raw.github.com/angular-ui/bootstrap/gh-pages/ui-bootstrap-tpls-0.7.0.js',
                    os.path.join(projectDir, 'src\\app\\lib\\'))

    # ------ app folder
    downloadFile(   gitResourceUri + 'res/index.html',
                    os.path.join(projectDir, 'src\\app\\'))
    downloadFile(   gitResourceUri + 'res/index-async.html',
                    os.path.join(projectDir, 'src\\app\\'))
    downloadFile(   gitResourceUri + 'res/.htaccess',
                    os.path.join(projectDir, 'src\\app\\'))
    downloadFile(   gitResourceUri + 'res/content/favicon.ico',
                    os.path.join(projectDir, 'src\\app\\'))

    # ------ content
    downloadFile(   gitResourceUri + 'res/content/apple-touch-icon.png',
                    os.path.join(projectDir, 'src\\app\\content\\images\\'))
    downloadFile(   gitResourceUri + 'res/content/apple-touch-icon-72x72.png',
                    os.path.join(projectDir, 'src\\app\\content\\images\\'))
    downloadFile(   gitResourceUri + 'res/content/apple-touch-icon-114x114.png',
                    os.path.join(projectDir, 'src\\app\\content\\images\\'))
    downloadFile(   gitResourceUri + 'res/content/bg.png',
                    os.path.join(projectDir, 'src\\app\\content\\images\\'))
    downloadFile(   gitResourceUri + 'res/content/partial1.html',
                    os.path.join(projectDir, 'src\\app\\content\\partials\\'))
    downloadFile(   gitResourceUri + 'res/content/partial2.html',
                    os.path.join(projectDir, 'src\\app\\content\\partials\\'))

    # ------ css
    downloadFile(   gitResourceUri + 'res/style/app.css',
                    os.path.join(projectDir, 'src\\app\\content\\css\\'))
    downloadFile(   gitResourceUri + 'res/style/bootstrap.css',
                    os.path.join(projectDir, 'src\\app\\content\\css\\'))
    downloadFile(   gitResourceUri + 'res/style/bootstrap-responsive.css',
                    os.path.join(projectDir, 'src\\app\\content\\css\\'))

    # ------ fonts
    downloadFile(   gitResourceUri + 'res/fonts/ubuntu-r-webfont.eot',
                    os.path.join(projectDir, 'src\\app\\content\\fonts\\'))
    downloadFile(   gitResourceUri + 'res/fonts/ubuntu-r-webfont.svg',
                    os.path.join(projectDir, 'src\\app\\content\\fonts\\'))
    downloadFile(   gitResourceUri + 'res/fonts/ubuntu-r-webfont.ttf',
                    os.path.join(projectDir, 'src\\app\\content\\fonts\\'))
    downloadFile(   gitResourceUri + 'res/fonts/ubuntu-r-webfont.woff',
                    os.path.join(projectDir, 'src\\app\\content\\fonts\\'))

    # ------ meta files
    downloadFile(   gitResourceUri + 'LICENSE',
                    projectDir)

    # ------ config
    downloadFile(   gitResourceUri + 'res/config/karma.conf.js',
                    os.path.join(projectDir, 'res\\config\\'))
    downloadFile(   gitResourceUri + 'res/config/karma-e2e.conf.js',
                    os.path.join(projectDir, 'res\\config\\'))

    # ------ error
    #    downloadFile(   gitResourceUri + 'res/fonts/ubuntu-r-webfont.woff',
    #                    os.path.join(projectDir, 'src\\app\\content\\fonts\\'))

    # ------ scripts
    downloadFile(   gitResourceUri + 'res/scripts/e2e-test.bat',
                    os.path.join(projectDir, 'res\\scripts\\'))
    downloadFile(   gitResourceUri + 'res/scripts/e2e-test.sh',
                    os.path.join(projectDir, 'res\\scripts\\'))
    downloadFile(   gitResourceUri + 'res/scripts/test.bat',
                    os.path.join(projectDir, 'res\\scripts\\'))
    downloadFile(   gitResourceUri + 'res/scripts/test.sh',
                    os.path.join(projectDir, 'res\\scripts\\'))
    downloadFile(   gitResourceUri + 'res/scripts/web-server.js',
                    os.path.join(projectDir, 'res\\scripts\\'))

    # ------ test
    downloadFile(   gitResourceUri + 'res/test/unit/controllersSpec.js',
                    os.path.join(projectDir, 'src\\test\\unit\\'))
    downloadFile(   gitResourceUri + 'res/test/unit/directivesSpec.js',
                    os.path.join(projectDir, 'src\\test\\unit\\'))
    downloadFile(   gitResourceUri + 'res/test/unit/filtersSpec.js',
                    os.path.join(projectDir, 'src\\test\\unit\\'))
    downloadFile(   gitResourceUri + 'res/test/unit/servicesSpec.js',
                    os.path.join(projectDir, 'src\\test\\unit\\'))

    downloadFile(   gitResourceUri + 'res/test/e2e/runner.html',
                    os.path.join(projectDir, 'src\\test\\e2e\\'))
    downloadFile(   gitResourceUri + 'res/test/e2e/scenarios.js',
                    os.path.join(projectDir, 'src\\test\\e2e\\'))

    # ------ js
    downloadFile(   gitResourceUri + 'res/js/app.js',
                    os.path.join(projectDir, 'src\\app\\js\\'))
    downloadFile(   gitResourceUri + 'res/js/controllers.js',
                    os.path.join(projectDir, 'src\\app\\js\\controllers\\'))
    downloadFile(   gitResourceUri + 'res/js/directives.js',
                    os.path.join(projectDir, 'src\\app\\js\\directives\\'))
    downloadFile(   gitResourceUri + 'res/js/filters.js',
                    os.path.join(projectDir, 'src\\app\\js\\filters\\'))
    downloadFile(   gitResourceUri + 'res/js/services.js',
                    os.path.join(projectDir, 'src\\app\\js\\services\\'))

    # ------ doc folder content

def replaceProjectName(projectDir, projectName):
    fileContent = []

    with open (os.path.join(projectDir, 'src\\app\\index.html'), "r") as indexFile:
        fileContent = indexFile.readlines()

    fullContent = re.sub('\{\{ProjectName\}\}', projectName, ''.join(fileContent))

    with open(os.path.join(projectDir, 'src\\app\\index.html'), 'w') as indexFile:
        indexFile.write(fullContent)

def main(argv):
    rootDir = ''
    projectName = ''
    projectType = ''

    try:
       opts, args = getopt.getopt(argv,"hr:n:t:",["rootDir=","projectName=","projectType="])
    except getopt.GetoptError:
    #        print 'createProject.py -i <inputfile> -o <outputfile>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
    #           print 'test.py -i <inputfile> -o <outputfile>'
            sys.exit()
        elif opt in ("-r", "--rootDir"):
            rootDir = arg
        elif opt in ("-n", "--projectName"):
            projectName = arg
        elif opt in ("-t", "--projectType"):
            projectType = arg

    if not rootDir:
        rootDir = 'p:\\'
    if projectName:
        projectDir = os.path.join(rootDir, projectName)
        createStructure(projectDir)
        fillWithLife(projectDir, projectName)
        replaceProjectName(projectDir, projectName)
        gitInitAndCommit(projectDir)
    else:
        sys.exit(2)

if __name__ == "__main__":
   main(sys.argv[1:])
