"use strict";

module.exports = function(grunt) {

  var pkg = require('./package.json');

  var conf = {
    clean: ['logs'],
    prompt: {
      setup: {
        options: {
          questions: [{
            config: 'app.name',
            type: 'list',
            message: 'App your working on?',
            choices: grunt.file.expand({
              filter: 'isDirectory'
            }, './apps/*').map(function(d) {
              return d.replace('./apps/', '')
            })
            }, {
            config: 'dev.plugin',
            type: 'input',
            message: 'Module to watch for changes ?',
            validate: function(name) {
              if (!name) return true;
              var dir = grunt.file.expand({
                filter: 'isDirectory'
              }, './node_modules/' + name);
              return dir.length === 1 || (name + " not found in ./node_modules (leave empty to ignore)");
            }
          }]
        }
      }
    },
    watch: {
      /*
      gruntfile: {
        files: "<%= jshint.gruntfile.src %>",
        //tasks: ["jshint:gruntfile"]
      },
      */
      css: {
        files: ['node_modules/<%= app.theme %>/public/css/*.css'],
        tasks: ['pine:newer:copy:css'],
        debounceDelay: 1000,
      },
      modScripts: {
        files: ['node_modules/<%= dev.plugin %>/html/scripts/*.js'],
        tasks: ['pine:newer:copy:scripts']
      }
    },
    nodemon: {
      dev: {
        script: 'index.js',
        options: {
          args: ['<%= app.name %>'],
          watch: [
            'node_modules/<%= app.theme %>/templates',
            'apps/<%= app.name %>/public/scripts'
          ],
          ext: 'html,js'
        }
      }
    },
    bump: {
      options: {
        commit: true,
        commitMessage: grunt.option("message") || 'Release v%VERSION%',
        commitFiles: ['-a'], // '-a' for all files
        createTag: false,
        push: true,
        pushTo: 'origin',
      }
    },
    copy: {
      css: {
        expand: true,
        cwd: 'node_modules/<%= app.theme %>/public/css',
        src: "*",
        dest: 'apps/<%= app.name %>/public/css/'
      },
      img: {
        expand: true,
        cwd: 'node_modules/<%= app.theme %>/public/img',
        src: ["*"],
        dest: './apps/<%= app.name %>/public/img'
      },
      scripts: {
        expand: true,
        cwd: 'node_modules/',
        src: ["{<%= app.conf.plugins %>}/html/scripts/**/*"],
        rename: function(dest, src) {
          return dest + src.replace(/^(.+)\/html\/scripts\/(.+)$/, '$1/$2');
        },
        dest: './apps/<%= app.name %>/public/scripts/'
      }
    },
    concurrent: {
      dev: {
        tasks: ['pine:nodemon:dev', 'pine:watch'],
        options: {
          logConcurrentOutput: true
        }
      }
    }
  }


  grunt.registerTask('pine', function() {
    var setup;
    try {
      setup = grunt.file.readJSON('./.pinedev');
    } catch (e) {
      grunt.log.error(e);
      if (e.origError && e.origError.code === 'ENOENT') {
        grunt.fail.warn('You haven\'t set up your pine dev settings. Run grunt pine:setup then retry');
      } else {
        grunt.fail.warn('Unable to read pine dev settings (.pinedev). Run grunt pine:setup then retry');
        throw e;
      }
      return false;
    }


    setup.app.dir = process.cwd() + "/apps/" + setup.app.name;
    setup.app.conf = require('pine/lib/conf.js')(setup.app.dir);


    if (setup.app.conf.html) {
      setup.app.theme = setup.app.conf.html.theme;
    } else {

      delete conf.copy;
      delete conf.watch.css;
      delete conf.watch.modScripts;
      conf.nodemon.dev.options.watch = ['index.js'];
      conf.nodemon.dev.options.ext;
      conf.nodemon.dev.options.ignore = ['**'];
      conf.concurrent.dev.tasks.pop();
    }


    grunt.config('app', setup.app);
    grunt.config('dev', setup.dev);

    grunt.log.subhead("Application " + setup.app);


    var _task = Array.prototype.slice.call(arguments, 0);
    grunt.task.run(_task.join(':'));

  });

  grunt.registerTask('pine:setupSave', function() {
    var pineSetup = {
      'app': grunt.config('app'),
      'dev': grunt.config('dev')
    }
    console.log(pineSetup);
    grunt.file.write('./.pinedev', JSON.stringify(pineSetup));
  });

  grunt.registerTask('pine:setup', ['prompt', 'pine:setupSave']);
  grunt.registerTask('serve', ['concurrent:dev'])

  require('load-grunt-tasks')(grunt);
  //require('./grunt/sync-versions.js')(grunt);
  // Project configuration.
  grunt.initConfig(conf);

};