Seq = require 'seq'
require './buildtools'

if 'function' is not typeof task
    throw new Error "'buildtools/tasks' can only be imported into Coke/Cake/Jake environment!"

# TODO: wrap task so you can pass deps?
coke_task   = task
coke_invoke = invoke



# task = globals.task = (name, desc='', deps=[], action) ->
#     switch @@.length
#     case 3
#         action = deps
#         if Array.isArray desc
#             [deps, desc] = [desc, '']
#         else
#             deps = []
#     case 2
#         if typeof desc is 'function'
#             [action, desc, deps] = [desc, '', []]
#         else if Array.isArray desc
#             [deps, desc] = [desc, '']
#     case 1
#         { name, desc, deps, action } = opts = name
#     action or= -> # opts.verbose and console.log "Stub task '#name'~"
#     opts or= { name, desc, deps, action }
#     unless name and typeof action is 'function'
#         throw new Error 'All tasks require a name and an action body!'
#     
#     
#     # XXX: Coke needs to pass a callback to enable async tasks
#     coke_task opts.name, opts.desc, ->
#         if opts.deps?.length
#             queue = Seq(opts.deps)
#                 .seqEach (dep) ->
#                     coke_invoke dep
#                     # <- coke_invoke dep, this
#                     @ok()
#                 .seq ->
#                     opts.action ...
#         else
#             opts.action ...



# task \link 'Link package source to node_modules so the name resolves correctly' ->
#     mkdirp 'node_modules'
#     if not exists MODULE_LINK
#         say "Creating #PROJECT_NAME symlink..."
#         fs.symlinkSync "../lib", MODULE_LINK

# task \server 'Start dev server' ->
#     invoke \link
#     invoke \update_version
#     run 'lib/server/server.co'

# task \build 'Build coco sources' ->
#     invoke \update_version
#     coco <[ -bjc package.co ]>

# task \test 'Rebuild test files and run tests' ->
#     invoke 'link'
#     tests = glob.globSync 'test/*.co'
#     tests.forEach (file) ->
#         js = file.replace '.co', '.js'
#         fs.unlinkSync js if exists js
#         coco [ '-bc', file ]
#     sh 'expresso'

# task \clean 'Clean up environment and artifacts' ->
#     remove [MODULE_LINK, 'var', 'tmp/dest'], true



# task \bundle 'Build and minify JS & CSS bundles for production' ->
#     invoke \bundle_js
#     invoke \bundle_css
# 
# task \bundle_js 'Build and minify JS' ->
#     outpath = "#VAR/lib/lib-bundle.js"
#     outmin = outpath.replace '.js', '.min.js'
#     
#     bundle_js do
#         outpath
#         <[  es5-shim modernizr json2
#             jquery jquery.history.min
#             require
#             underscore.mod underscore.string.mod
#             backbone.mod
#         ]>
#         paths : "static/lib var/lib", minify:false
#     
#     say 'Compressing', outpath.white.bold, 'to', outmin.magenta.bold,  '...'
#     write outmin, minify(read outpath), 'utf8'
# 
# task \bundle_css 'Build and minify CSS' ->
#     bundle_css do
#         "var/css/site-bundle.css"
#         "reset gamebook tipsy"
#         paths: "static/css var/css"
# 



# task \build 'Build coco sources' ->
#     invoke \setup
#     coco <[ -bjc package.co ]>
#     
#     {sources} = require 'limn/server/view-helpers'
#     browserify = require 'browserify'
#     Coco       = require 'coco'
#     Jade       = require 'jade'
#     Stylus     = require 'stylus'
#     nib        = require 'nib'
#     yaml       = require 'js-yaml'
#     
#     matchExt = /((?:\.min)?)\.mod((?:\.min)?)\.js$/i
#     
#     console.log 'Building source...'
#     Seq()
#         .seq ->
#             console.log '  Bundling Browserify bundle'
#             bundle = browserify exports:<[ require process ]>
#                 .require <[ seq d3 events ]>
#                 .bundle()
#             write 'static/vendor/browserify.js', bundle
#             @ok()
#         
#         .set glob 'src/template/**/*.jade', {+sync}
#         .seqEach (infile) ->
#             outfile     = "#infile.js".replace /^src/, 'lib'
#             console.log "  Compiling Jade template to JS:\t #infile \t-->\t #outfile"
#             template_fn = Jade.compile read(infile), { +pretty, +client, -compileDebug, filename:infile }
#             template    = String template_fn .replace /^function anonymous\(/, 'function \('
#             mkdirp dirname outfile
#             write outfile, """
#                 var template = #template;
#                 if (typeof module != 'undefined') {
#                     module.exports = exports = template;
#                 }
#             """
#             @ok()
#         
#         .set glob 'src/**/*.co', {+sync}
#         .seqEach (infile) ->
#             return @ok() unless exists infile
#             outfile = infile.replace /^src/, 'lib' .replace /\.co$/, '.js'
#             console.log "  Compiling Coco to JS:\t #infile \t-->\t #outfile"
#             mkdirp dirname outfile
#             write outfile, Coco.compile read(infile), {+bare, filename:infile}
#             @ok()
#         
#         .set sources("www/modules.yaml", 'development').map -> it.slice 1
#         .seqEach (srcfile) ->
#             return @ok() unless matchExt.test srcfile
#             outfile = (if _.startsWith srcfile, 'vendor' then 'static' else 'www') + '/' + srcfile
#             infile = outfile.replace matchExt, '$1$2.js'
#             return @ok() unless exists infile
#             return @ok() if _.startsWith(srcfile, 'vendor') and exists outfile
#             parts = infile.replace matchExt, '' .split '/' .slice 2
#             parts.pop() if 'index' is _.last parts
#             ID = parts.join '/' 
#             console.log "  Wrapping JS in Module:\t #infile \t-->\t #outfile"
#             mkdirp dirname outfile
#             write outfile, "require.define('/node_modules/#ID.js', function(require, module, exports, __dirname, __filename, undefined){\n\n" + read(infile) + "\n\n});\n"
#             @ok()
#         
#         .set glob 'www/css/*.styl', {+sync}
#         .seqEach (infile) ->
#             outfile = infile.replace /\.styl$/, '.css'
#             console.log "  Compiling Stylus to CSS:\t #infile \t-->\t #outfile"
#             mkdirp dirname outfile
#             stylus = Stylus read infile
#             stylus.set 'filename', infile
#             stylus.use nib()
#             stylus.render (err, css) ~>
#                 write outfile, css unless err
#                 this err
#         
#         .set glob 'www/schema/**/*.yaml', {+sync}
#         .seqEach (infile) ->
#             outfile = infile.replace /\.yaml$/, '.json'
#             console.log "  Compiling YAML to JSON:\t #infile \t-->\t #outfile"
#             mkdirp dirname outfile
#             write outfile, JSON.stringify yaml.load read infile
#             @ok()
#         
#         .catch (err) ->
#             console.error "Error! #err", err
#             err = new Error err if typeof err is 'string'
#             throw err
#         .seq ->
#             console.log 'Done!'
#         
# 
# task \bundle 'Build application and vendor bundles' ->
#     invoke \bundle_app
#     invoke \bundle_vendor
# 
# task \bundle_app 'Build application bundle' ->
#     {sources} = require 'limn/server/view-helpers'
#     
#     app_bundle_path = 'var/js/limn/app-bundle.js'
#     app_sources = sources("www/modules.yaml", 'development')
#         .filter -> not _.startsWith it, '/vendor'
#         .map -> it.slice 1 .replace /js\/limn/, 'lib'
#     mkdirp dirname app_bundle_path
#     bundle_js app_bundle_path, app_sources, {-minify}
#     
#     app_bundle_min_path = app_bundle_path.replace /\.js$/, '.min.js'
#     print 'Minifying into', app_bundle_min_path.magenta.bold, '... '
#     write app_bundle_min_path, minify read app_bundle_path
#     say 'ok.\n'
# 
# task \bundle_vendor 'Build vendor bundle' ->
#     {sources} = require 'limn/server/view-helpers'
#     
#     vendor_bundle_path = 'var/vendor/vendor-bundle.js'
#     vendor_sources = sources("www/modules.yaml", 'development')
#         .filter -> _.startsWith it, '/vendor'
#         .map -> "static#it"
#     mkdirp dirname vendor_bundle_path
#     bundle_js vendor_bundle_path, vendor_sources, {-minify}
#     
#     vendor_bundle_min_path = vendor_bundle_path.replace /\.js$/, '.min.js'
#     print 'Minifying into', vendor_bundle_min_path.magenta.bold, '... '
#     write vendor_bundle_min_path, minify read vendor_bundle_path
#     say 'ok.\n'
# 
# 
# 



task \version 'Determine git version' ->
    version <- getVersion
    say 'Version is', version.white.bold


task \update_version 'Updates server/version.js' ->
    version <- getVersion
    print 'Writing', 'lib/version.js'.white.bold, 'with', version.white.bold, '... '
    mkdirp 'lib'
    write 'lib/version.js', "module.exports = exports = '#{version}';\n", 'utf8'
    say 'ok!'.green.bold


