module.exports = function (grunt) {
    require('time-grunt')(grunt);
    require('load-grunt-tasks')(grunt);

    var pkg = grunt.file.readJSON('package.json');
	var localConfig = {
			app: 'scheduling-manager',
            dist: 'dist',
            build: 'build',
            testUrl: 'http://localhost:8080/scheduling-manager/test/',
            dest: process.env.CATALINA_HOME + '/webapps/scheduling-manager/'
		},
		publishRelease = function (err, stdout, stderr, cb) {
			if (!err) {
				grunt.config.set('artifactory.release.options', {
					url: 'https://ihealthbuild.agilexhealth.com',
					repository: 'agilex',
					username: 'admin',
					password: 'Agilexadmin99$',
					publish: [
						{
							id: 'com.agilex.web:' + pkg['artifact-name'] + ':war',
							version: pkg.version + '.' + stdout.trim(),
							path: 'build/'
						}
					]
				});
				grunt.task.run('artifactory:release:publish');
			} else {
				console.log('Command to get Git commit count failed');
				console.log(err);
				console.log(stderr);
			}
			cb();
		};

	grunt.initConfig({
		pkg: pkg,
		config: localConfig,
		qunit_junit: {
			options: {
				dest: './test'
			}
		},
        clean:{
            dist:['.tmp', '<%= config.dist %>/*']
        },
        jshint: {
            options: {
                jshintrc: '.jshintrc',
                reporter: require('jshint-stylish')
            },
            all: [
                'Gruntfile.js',
                '<%= config.app %>/js/**/*.js',
                'test/spec/{,*/}*.js'
            ]
        },
		requirejs: { // base task that optimize (multitask) will use
            dist: {
                options: {
                    baseUrl: '<%= config.app %>/app/js',
                    optimize: 'none',
                    preserveLicenseComments: false,
                    useStrict: true,
                    wrapShim: true,
                    wrap: true
                }
            }
		},
        useminPrepare: {
            options: {
                dest: '<%= config.dist %>'
            },
            html: '<%= config.app %>/index.html'
        },
        usemin: {
            options: {
                dirs: ['<%= config.dist %>']
            },
            html: ['<%= config.dist %>/{,*/}*.html'],
            css: ['<%= config.dist %>/app/css/{,*/}*.css']
        },
        imagemin: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '<%= config.app %>/app/images',
                    src: '{,*/}*.{png,jpg,jpeg}',
                    dest: '<%= config.dist %>/app/images'
                }]
            }
        },
        htmlmin: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '<%= config.app %>',
                    src: '*.html',
                    dest: '<%= config.dist %>'
                }]
            }
        },
        copy: {
            dist: {
                files: [{
                    expand: true,
                    dot: true,
                    cwd: '<%= config.app %>',
                    src: [
                        '*.{ico,txt,png,json,pdf}',
                        'app/css/fonts/{,*/}*.*',
                        'libs/css/images/*.{gif,png}'
                    ],
                    dest: '<%= config.dist %>'
                },{
                    expand: true,
                    flatten: true,
                    dot: true,
                    cwd: '<%= config.app %>',
                    src: ['libs/css/images/*.{gif,png}'],
                    dest: '<%= config.dist %>/app/css/images'
                }]
            },
            dev: {
                files: [{
                    expand: true,
                    dot: true,
                    cwd: '<%= config.app %>',
                    src: ['**'],
                    dest: '<%= config.dist %>'
                }]
            },
            toTomcat:{
                expand: true,
                cwd: '<%= config.dist %>/scheduling-manager/',
                src: ['**'],
                dest: '<%= config.dest %>/'
            },
            toBuild:{
                src: ['<%= config.app %>/**'],
                dest: '<%= config.dist %>/'
            },
            'app': {
                files: [
                    {
                        dest: '<%= config.dest %>/', cwd: '<%= config.app  %>', src: ['<%= config.appLocation %>**'], expand: true
                    }
                ]
            },
            'test': {
                files: [
                    {
                        expand: true, cwd: '<%= config.app  %>', dest: '<%=  config.dest %>', src: ['test/**', '!test']
                    }
                ]
            },
            'other': {
                files: [
                    {
                        expand: true, cwd: '<%= config.app  %>', dest: '<%=  config.dest %>', src: ['**', '!{test/**,<%= config.appLocation %>**}']
                    }
                ]
            }
        },
        rev: {
            dist: {
                files: {
                    src: [
                        '<%= config.dist %>/app/js/{,*/}*.js',
                        '<%= config.dist %>/app/css/{,*/}*.css'
                    ]
                }
            }
        },
		watch: {
			options:{
				'atBegin':true
			},
			app: {
				'files': '<%= config.app + config.appLocation %>**', tasks: ['copy:app']
			}
			, 'test': {
				files: [
					'<%= config.app %>test/**'
				], tasks: ['copy:test']
			}

		},
		shell: {
			testApp: {
				command: 'node_modules/phantomjs/bin/phantomjs <%= config.app %>test/runner.js <%= config.testUrl  %> 1200',
				options: {
					stdout: true
				}
			},
			version: {
				command: 'git log -1 --pretty=format:%h',
				options: {
					callback: function log(err, stdout, stderr, cb) {
						console.dir(stdout);
						grunt.file.write('scheduling-manager/version.json', JSON.stringify({
							version: pkg['version'],
							metaRevision: stdout,
							date: grunt.template.today()
						}));
						cb();
					}
				}
			},
			revision: {
				command: 'git rev-list HEAD --count',
				options: {
					callback: function log(err, stdout, stderr, cb) {
						console.dir(stdout);
						grunt.file.write('scheduling-manager/version.json', JSON.stringify({
							version: pkg['version'],
							build: stdout.replace('\n', ''),
							metaRevision: grunt.file.readJSON('scheduling-manager/version.json')['metaRevision'],
							date: grunt.template.today()
						}));
						cb();
					}
				}
			},
			publishRelease: {
				command: 'git rev-list HEAD --count',
				options: {
					callback: publishRelease
				}
			}
		},
		artifactory: {
			options: {
				url: 'https://ihealthbuild.agilexhealth.com',
				repository: 'agilex',
				username: 'admin',
				password: 'Agilexadmin99$'
			},
			snapshot: {
				files: [
					{ src: ['<%= config.build %>/scheduling-manager/**/*', '!**/test/**/*'] }
				],
				options: {
					publish: [
						{
							id: 'com.agilex.web:' + pkg['artifact-name'] + ':war',
							version: pkg['artifact-name'] + '-SNAPSHOT',
							path: '<%= config.build %>/war/'
						}
					]
				}
			},
			release: {
				files: [
					{ src: [
						'scheduling-manager/**/*',
						'!**/test/**/*'
					] }
				]
			}
		}
	});

	grunt.registerTask('webTest', ['shell:testApp']);
	grunt.registerTask('test', ['qunit:unit']);
	grunt.registerTask('providerTest');
	grunt.registerTask('default', ['clean:build', 'deploy']);
	grunt.registerTask('cleanNonMinCSS', ['clean:nonMinCSS']);
	grunt.registerTask('version', ['shell:version']);
	grunt.registerTask('sqaVersion', ['version', 'shell:revision']);
	grunt.registerTask('css-minify', ['cssmin', 'cleanNonMinCSS']);
	grunt.registerTask('deployToTomcat', ['copy:toTomcat']);
	grunt.registerTask('buildAndMinify', ['copy:toBuild', 'css-minify', 'uglify:build']);
	grunt.registerTask('copyCode', ['copy:app', 'copy:test', 'copy:other']);
	grunt.registerTask('deploy', ['version', 'clean', 'copyCode'] );
	grunt.registerTask('sqaDeploy', ['sqaVersion', 'clean', 'copyCode']);
	grunt.registerTask('provider', ['clean', 'deploy', 'providerTest']);
	grunt.registerTask('sqaRelease', ['sqaVersion', 'shell:publishRelease']);
	grunt.registerTask('release', ['version', 'shell:publishRelease']);

    grunt.registerTask('build', [
        'clean:dist',
        'useminPrepare',
        'requirejs',
        'imagemin',
        'htmlmin',
        'concat',
        'cssmin',
        'uglify',
        'shell:version',
        'copy:dist',
        'rev',
        'usemin'
    ]);
    
    grunt.registerTask('sqabuild', [
        'clean:dist',
        'useminPrepare',
        'requirejs',
        'imagemin',
        'htmlmin',
        'concat',
        'cssmin',
        'uglify',
        'sqaVersion',
        'copy:dist',
        'rev',
        'usemin'
    ]);

    grunt.registerTask('default', [
        'jshint',
        'test',
        'build'
    ]);
    grunt.registerTask('devBuild', [
        'clean:dist',
        'shell:version',
        'copy:dev'
    ]);

};

