#
# The new project generator tool
#
# Copyright (C) 2011-2012 Nikolay Nemshilov
#
fs       = require('fs')
lovelyrc = require('../lovelyrc')

placeholders = {}

#
# Starts the new project generation
#
# @param {String} projectname
# @param {Array} the rest of the arguments
# @return void
#
generate = (projectname, args) ->
  directory    = "#{process.cwd()}/#{projectname}"
  project_tpl  = "#{__dirname}/../project_tpl"
  use_coffee   = args.indexOf('--js')     is   -1 && lovelyrc.lang.indexOf('js')     is   -1
  use_sass     = args.indexOf('--css')    is   -1 && lovelyrc.lang.indexOf('css')    is   -1
  use_scss     = args.indexOf('--scss')   isnt -1 || lovelyrc.lang.indexOf('scss')   isnt -1
  use_stylus   = args.indexOf('--stylus') isnt -1 || lovelyrc.lang.indexOf('stylus') isnt -1
  use_sass     = !use_scss && !use_stylus && use_sass
  use_css      = !use_sass && !use_scss   && !use_stylus


  placeholders =
    projectname: projectname,
    projectunit: projectname.replace(/(^|-)([a-z])/g, (m,m1,m2)-> m2.toUpperCase())
    projectfile: projectname.replace(/\-/g, '_')
    year:        new Date().getFullYear(),
    username:    lovelyrc.name || "Vasily Pupkin"


  print "Creating directory: #{projectname}"
  fs.mkdirSync(directory, 0o0755)

  # just checking if the file should be copied over
  suitable = (filename) ->
    switch filename.split('.').pop()
      when 'js'     then return !use_coffee
      when 'coffee' then return  use_coffee
      when 'sass'   then return  use_sass
      when 'scss'   then return  use_scss
      when 'styl'   then return  use_stylus
      when 'css'    then return  use_css
      else               return  true

  for filename in fs.readdirSync(project_tpl)
    if suitable(filename)
      source = fs.readFileSync("#{project_tpl}/#{filename}").toString()
      filename = '.gitignore' if filename is 'gitignore'

      print " - #{filename}"
      fs.writeFileSync("#{directory}/#{filename}", patch_source(source))


  print " - src/"
  fs.mkdirSync("#{directory}/src", 0o0755)

  filename = "#{placeholders.projectfile}.#{
    if use_coffee then 'coffee' else 'js'
  }"

  source = if use_coffee then """
  #
  # Project's main unit
  #
  # Copyright (C) %{year} %{username}
  #
  """ else """
  /**
   * Project's main unit
   *
   * Copyright (C) %{year} %{username}
   */
  """

  print " - src/#{filename}"
  fs.writeFileSync("#{directory}/src/#{filename}", patch_source(source))

  print " - test/"
  fs.mkdirSync("#{directory}/test", 0o0755)

  filename = "#{placeholders.projectfile}_test.#{
    if use_coffee then 'coffee' else 'js'
  }"

  source = if use_coffee then """
  #
  # Project's main unit test
  #
  # Copyright (C) %{year} %{username}
  #
  {Test, assert} = require('lovely')

  describe "%{projectunit}", ->
    %{projectunit} = window = document = $ = null

    before Test.load (build, win)->
      %{projectunit} = build
      window   = win
      document = win.document
      $        = win.Lovely.module('dom')

    it "should have a version", ->
      assert.ok %{projectunit}.version


  """ else """
  /**
   * Project's main unit test
   *
   * Copyright (C) %{year} %{username}
   */
  var Lovely = require('lovely');
  var Test   = Lovely.Test;
  var assert = Lovely.assert;

  describe("%{projectunit}", function() {
    var %{projectunit}, window, document, $;

    before(Test.load(function(build, win) {
      %{projectunit} = build;
      window   = win;
      document = win.document;
      $        = win.Lovely.module('dom');
    }));

    it("should have a version number", function() {
      assert.ok(%{projectunit}.version);
    });
  });

  """

  print " - test/#{filename}"
  fs.writeFileSync("#{directory}/test/#{filename}", patch_source(source))

  print " - build/"
  fs.mkdirSync("#{directory}/build", 0o0755)


# fills in all the placeholders
patch_source = (source)->
  for key of placeholders
    source = source.replace(
      new RegExp('%\\{'+ key + '\\}', 'g'), placeholders[key])

  source


exports.init = (args) ->
  name_re = ///
    ^[a-z0-9]     # it should start with a letter or a number
    [a-z0-9\-]+   # should hase only alpha-numberic symbols
    [a-z0-9]$     # end with a letter or a number
  ///

  project_name = args.shift()

  if !project_name
    print_error "You have to specify the project name"

  if !name_re.test(project_name)
    print_error "Project name should match: " + name_re.toString().yellow

  if fs.existsSync("#{process.cwd()}/#{project_name}")
    print_error "Directory already exists"

  generate(project_name, args)



exports.help = (args) ->
  """
  Generates a standard LovelyIO module project

  Usage:
      lovely new <project-name>

  Options:
      --js         use JavaScript for scripting
      --css        use CSS for styles
      --scss       use SCSS for styles
      --stylus     use Stylus for styles

  """
