var simplePersist = require('./data/simple-persist');

module.exports = function(grunt) {

    'use strict';

    var renkan_src = [
        'dist/js/templates.js',
        'js/main.js',
        'js/router.js',
        'js/dataloader.js',
        'js/models.js',
        'js/defaults.js',
        'js/i18n.js',
        'js/full-json.js',
        'js/save-once.js',
        'js/ldtjson-bin.js',
        'js/list-bin.js',
        'js/wikipedia-bin.js',
        'dist/js/paper-renderer.js',
    ];

    var renkan_banner = grunt.file.read('js/header.js').toString() +
        '\n/*! <%= pkg.name %> - v<%= pkg.version %> - Copyright © IRI ' +
        '<%= grunt.template.today("yyyy") %> */\n\n';

    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        requirejs: {
            renderer: {
                options: {
                    baseUrl: "js/",
                    name: "main-renderer",
                    out: "dist/js/paper-renderer.js",
                    optimize: "none",
                    beautify: true,
                    paths: {
                        requtils: "require-utils",
                        jquery: "empty:",
                        underscore: "empty:",
                        filesaver: "empty:",
                        'ckeditor-core': "empty:",
                        'screenfull': "empty:"
                    },
                    include: [ "jquery-private"],
                }
            }
        },
        jst: {
            compile: {
                options: {
                    namespace: 'renkanJST',
                    //amd: true
                },
                files: {
                    "dist/js/templates.js": ["templates/**/*.html"]
                }
            }
        },
        uglify: {
            options: {
                banner: renkan_banner,
                sourceMap: true,
                sourceMapIncludeSources: true
            },
            renkan: {
                files: {
                    'dist/js/renkan.min.js': renkan_src
                }
            }
        },
        concat: {
            options: {
                banner: renkan_banner
            },
            renkan: {
                files: {
                    'dist/js/renkan.js': renkan_src
                }
            }
        },
        clean: {
            options: {
                force: true
            },
            renderer: ["dist/js/paper-renderer.js"],
            jst: ["dist/js/templates.js"],
            renkan: ["dist/"],
            lib: ["lib/"],
            bower: ["bower_components/"]
        },
        cssmin: {
            options: {
                banner: renkan_banner
            },
            renkan: {
                expand: true,
                cwd: 'css/',
                src: ['*.css'],
                dest: 'dist/css',
                ext: '.min.css'
            }
        },
        copy: {
            vendors: {
                files: [{
                    expand: true,
                    cwd: 'vendors/',
                    src: ['**'],
                    dest: 'lib/'
                }],
            },
            renkan: {
                files: [{
                    expand: true,
                    cwd: '',
                    src: ['img/*'],
                    dest: 'dist/',
                    filter: 'isFile'
                }, {
                    expand: true,
                    cwd: '',
                    src: ['data/properties.json'],
                    dest: 'dist/',
                    filter: 'isFile'
                }, {
                    expand: true,
                    cwd: '',
                    src: ['lib/**'],
                    dest: 'dist/'
                }]
            },
            renkan_css: {
                options: {
                    process: function(content, srcpath) {
                        return grunt.template.process(renkan_banner) + content;
                    }
                },
                files: [{
                    expand: true,
                    cwd: '',
                    src: ['css/*'],
                    dest: 'dist/',
                    filter: 'isFile'
                }]
            },
            renkan_server: {
                files: [{
                    expand: true,
                    cwd: 'dist',
                    src: ['**', '!data/*', '!lib/**'],
                    dest: '../server/python/django/renkanmanager/static/renkanmanager/lib/renkan/',
                    filter: 'isFile'
                }, {
                    expand: true,
                    cwd: 'dist/lib',
                    src: ['**'],
                    dest: '../server/python/django/renkanmanager/static/renkanmanager/lib/',
                    filter: 'isFile'
                }, {
                    expand: true,
                    cwd: 'dist',
                    src: ['**', '!data/*', '!lib/**'],
                    dest: '../server/python/django2/renkanmanager/static/renkanmanager/lib/renkan/',
                    filter: 'isFile'
                }, {
                    expand: true,
                    cwd: 'dist/lib',
                    src: ['**'],
                    dest: '../server/python/django2/renkanmanager/static/renkanmanager/lib/',
                    filter: 'isFile'
                }, {
                    expand: true,
                    cwd: 'dist',
                    src: ['**', '!data/*', '!lib/**'],
                    dest: '../server/php/basic/public_html/static/lib/renkan/',
                    filter: 'isFile'
                }, {
                    expand: true,
                    cwd: 'dist/lib',
                    src: ['**'],
                    dest: '../server/php/basic/public_html/static/lib/',
                    filter: 'isFile'
                }]
            }
        },
        jshint: {
            options: {
                curly: true,
                eqeqeq: true,
                eqnull: true,
                browser: true,
                esnext: true,
                globals: {
                    jQuery: true
                },
            },
            all: [
                'Gruntfile.js',
                'js/**/*.js',
                'data/simple-persist.js'
            ]
        },
        bower: {
            install: {
                options: {
                    targetDir: './lib',
                    layout: 'byComponent',
                    install: true,
                    verbose: false,
                    cleanTargetDir: true,
                    cleanBowerDir: false,
                    bowerOptions: {}
                }
            }
        },
        watch: {
            css: {
                files: ['css/**/*.css'],
                tasks: ['cssmin', 'copy:renkan_css'],
            },
            js: {
                files: ['js/**/*.js', 'templates/**/*.html'],
                tasks: ['jshint', 'requirejs', 'jst', 'concat', 'uglify', 'copy:renkan', 'clean:renderer'],
            },
            lib: {
                files: ['bower.json'],
                tasks: ['bower:install', 'copy:vendors', 'copy:renkan'],
            },
            vendors: {
                files: ['vendors/**'],
                tasks: ['copy:vendors', 'copy:renkan'],
            },
            options: {
                interrupt: true,
            },
        },
        connect: {
            server: {
                options: {
                    port: 9001,
                    base: '.',
                    useAvailablePort: true,
                    debug: true,
                    middleware: function(connect, options, middlewares) {
                        middlewares.unshift(simplePersist.middleware);
                        return middlewares;
                    }
                },
            }
        },
        umd: {
            'screenfull': {
                options: {
                    src: 'lib/screenfull/screenfull.js',
                    dest: 'lib/screenfull/screenfull-umd.js',
                    objectToExport: 'screenfull',
                    amdModuleId: 'screenfull'
                }
            },
        },
        replace: {
            'version-bower-package': {
                src: ['package.json', 'bower.json'],
                overwrite: true,
                replacements: [{
                    from: /^(\s+)\"version\"\:\s*\"([\d\.]+)\"\,[ \t]*$/m,
                    to: "$1\"version\"\: \"<%= setversion.version %>\",",
                }]
            },
            'version-gradle': {
                src: ['../server/java/build.gradle'],
                overwrite: true,
                replacements: [{
                    from: /^(\s+)version\s*\=\s*\'([\d\.]+)\'[ \t]*$/m,
                    to: "$1version = \'<%= setversion.version %>\'",
                }]
            },
            'version-maven': {
                src: ['../server/java/pom.xml', '../server/java/renkan-core/pom.xml', '../server/java/renkan-web/pom.xml', '../server/java/renkan-management/pom.xml'],
                overwrite: true,
                replacements: [{
                    from: /^(\s+)<version>\s*([\d\.]+)\s*<\/version>[ \t]*$/m,
                    to: "$1<version><%= setversion.version %></version>",
                }]
            },
            'version-django': {
                src: ['../server/python/django/renkanmanager/__init__.py'],
                overwrite: true,
                replacements: [{
                    from: /^(\s*)VERSION\s*=\s*\([ \t]*\d+[ \t]*,[ \t]*\d+[ \t]*,[ \t]*\d+[ \t]*,[ \t]*\"final\"[ \t]*\,[ \t]*0[ \t]*\)[ \t]*$/m,
                    to: function(matchedWord, index, fullText, regexMatches) {
                        var array_version = grunt.config.get('setversion.version').split('.');
                        var array_version_length = array_version.length;
                        for(let i=0;i<3-array_version_length;i++) {
                            array_version.push('0');
                        }
                        return regexMatches[0]+"VERSION = (" + array_version.join(', ') + ", \"final\", 0)";
                    },
                }]
            },
            'version-django2': {
                src: ['../server/python/django2/renkanmanager/__init__.py'],
                overwrite: true,
                replacements: [{
                    from: /^(\s*)VERSION\s*=\s*\([ \t]*\d+[ \t]*,[ \t]*\d+[ \t]*,[ \t]*\d+[ \t]*,[ \t]*\"final\"[ \t]*\,[ \t]*0[ \t]*\)[ \t]*$/m,
                    to: function(matchedWord, index, fullText, regexMatches) {
                        var array_version = grunt.config.get('setversion.version').split('.');
                        var array_version_length = array_version.length;
                        for(let i=0;i<3-array_version_length;i++) {
                            array_version.push('0');
                        }
                        return regexMatches[0]+"VERSION = (" + array_version.join(', ') + ", \"final\", 0)";
                    },
                }]
            },
        },
    });

    // Load the plugins.
    grunt.loadNpmTasks('grunt-contrib-requirejs');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-bower-task');
    grunt.loadNpmTasks('grunt-contrib-jst');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-umd');
    grunt.loadNpmTasks('grunt-text-replace');

    // Default task(s).
    grunt.registerTask('base', [
        'jshint',
        'bower:install',
        'copy:vendors',
        'clean:renkan',
        'requirejs',
        'jst',
        'concat',
        'uglify',
        'cssmin',
        'umd:screenfull',
        'copy:renkan',
        'copy:renkan_css',
        'clean:renderer',
    ]);
    grunt.registerTask('default', ['base', 'clean:jst']);
    grunt.registerTask('copy-server', 'copy files to server part', function() {
        grunt.task.run(['copy:renkan_server']);
    });
    grunt.registerTask('dev', ['base', 'connect:server', 'watch']);
    grunt.registerTask('set-version', function(version) {
        grunt.config.set('setversion.version', version);
        grunt.task.run(['replace:version-bower-package', 'replace:version-gradle', 'replace:version-maven', 'replace:version-django', 'replace:version-django2']);
    });


};
