var gulp = require('gulp');
var concat = require('gulp-concat');
var typescript = require('gulp-typescript');
var uglify = require('gulp-uglify');
var gutil = require('gulp-util'); 
var argv = require('yargs').argv;
var gulpif = require('gulp-if');
var fc2json = require('gulp-file-contents-to-json');
var header = require("gulp-header");
var sass = require('gulp-sass');
var cleanCss = require('gulp-clean-css');
var es = require("event-stream");
var livereload = require('gulp-livereload');
var wait = require('gulp-wait');

gulp.task('default', ['xCompileTs', 'xBundleJs', 'xBundleCss'], function () { });

// bsc> this task will also be run by TFS. Its not needed for local development
gulp.task('templatesToJson', function () {
    return gulp.src('./Modules/**/*.html')
        .pipe(fc2json('TemplateFiles.json'))
        .pipe(gulp.dest('./app_data'));
});

var sassFiles = [
    'Base/Content/styles.scss',
    'Base/Content/BootstrapWrapperV2.scss',
    'Base/Content/BootstrapNoWrappedV2.scss',
    'Base/Content/view-admin-htmltemplates.scss',
    'Modules/Branding/Content/WizdomV3.scss',
    'Modules/Charts/Content/style.scss',
    'Modules/Birthday/Content/Style.scss',
    'Modules/Noticeboard/Content/styles.scss',
    'Modules/PersonalLink/Content/styles.scss',
    'Modules/Wizdom365/Content/style.scss',
    'Modules/Megamenu/Content/Style.scss',
    'Modules/Megamenu/Content/AdminStyle.scss',
    'Modules/DepartmentUsers/Content/style.scss',
    'Modules/EditorRevision/Content/styles.scss',
    'Modules/Employees/Content/style.scss',
    'Modules/FAQ/Content/style.scss',
    'Modules/Gamification/Content/custom.scss',
    'Modules/ImageSlider/Content/Styles.scss',
    'Modules/Manual/Content/style.scss',
    'Modules/Phonebook/Content/styles.scss',
    'Modules/Poll/Content/style.scss',
    'Modules/ProfileProgress/Content/style.scss',
    'Modules/ProjectSpace/Content/style.scss',
    'Modules/ProjectSpace/Content/AdminStyle.scss',
    'Modules/Weather/Content/style.scss',
    'Modules/ProjectSpace/Content/style.scss',
    'Modules/Currentmenu/Content/Styles.scss',
    'Modules/Kanban/Content/style.scss',
    'Modules/CanteenMenu/Content/style.scss',
    'Modules/PageTranslation/Content/style.scss',
    'Modules/CourseManagement/Content/style.scss',
    'Modules/Yammer/Content/Style.scss',
    'Modules/Style/Content/AdminStyle.scss',
    'Modules/Webform/Content/style.scss',
    'Modules/Helpdesk/Content/style.scss',
    'Modules/Helpdesk/Content/AdminStyle.scss'
];
var cssBundles = [
    {
        outFile: "./Base/Bundles/styles.css",
        src: [
            "Base/Content/EncodingFix.css",
            "Base/Content/noty/animate.css",
            "Base/Content/noty/noty.css",
            "Base/Scripts/angular-tree-control/css/tree-control-attribute.css",
            "Base/Scripts/angular-tree-control/css/tree-control.css"
        ]
    },
    {
        outFile: "./Base/Bundles/EndUserStyles.css",
        src: [
            "Base/Content/EncodingFix.css",
            "Base/Content/video-js.css",
            "Base/Content/mentio.css",
            "Base/Content/morris.css",
            "Base/Scripts/scrollbar/perfect-scrollbar.css"
        ]
    },
    {
        outFile: "./Base/Bundles/AdminStyles.css",
        src: [
            "Base/Content/EncodingFix.css",
            "Base/Content/styles.css",
            "Base/Content/view-admin-htmltemplates.css",
            "Base/Content/colorpicker.css",
            "Base/Content/angular-swagger/swagger-ui.css",
            "Modules/Megamenu/Content/AdminStyle.css",
            "Modules/PersonalLink/Content/styles.css",
            "Modules/Gamification/Content/custom.css",
            "Modules/ProjectSpace/Content/AdminStyle.css",
            "Base/Content/glyphicons.css",
            "Base/Content/glyphicons-bootstrap.css",
            "Base/Content/office365.css",
            "Modules/Yammer/Content/style.css",
            "Modules/Style/Content/AdminStyle.css",
            "Modules/Helpdesk/Content/AdminStyle.css"
        ]
    },
    {
        outFile: "./Base/Bundles/StylesBootstrap.css",
        src: [
            "Base/Content/bootstrapwrapperv2.css"
        ]
    },
    {
        outFile: "./Base/Bundles/StylesBootstrapNoWrapped.css",
        src: [
            "Base/Content/EncodingFix.css",
            "Base/Content/BootstrapNoWrappedV2.css",
            "Base/Content/glyphicons.css",
            "Base/Content/glyphicons-bootstrap.css"
        ]
    },
    {
        outFile: "./Base/Bundles/StylesModules.css",
        src: [
            "Base/Content/EncodingFix.css",
            "modules/branding/content/wizdomv3.css",
            "Modules/ImageSlider/Content/Styles.css",
            "Modules/Currentmenu/Content/Styles.css",
            "Modules/TemplateManager/Content/styles.css",
            "Modules/EditorRevision/Content/styles.css",
            "Modules/Phonebook/Content/styles.css",
            "Modules/Manual/Content/style.css",
            "Modules/Gamification/Content/custom.css",
            "Modules/Employees/Content/style.css",
            "Modules/ProfileProgress/Content/style.css",
            "Modules/DepartmentUsers/Content/style.css",
            "Modules/Megamenu/Content/Style.css",
            "Modules/CorporateNews/Content/styles.css",
            "Modules/Noticeboard/Content/styles.css",
            "Modules/PersonalLink/Content/styles.css",
            "Modules/Wizdom365/Content/linkPreview.css",
            "Modules/Wizdom365/Content/style.css",
            "Modules/Birthday/Content/Style.css",
            "Modules/Weather/Content/style.css",
            "Modules/Charts/Content/style.css",
            "Modules/Poll/Content/style.css",
            "Modules/FAQ/Content/style.css",
            "Modules/ProjectSpace/content/style.css",
            "Modules/Kanban/Content/style.css",
            "Modules/CanteenMenu/Content/style.css",
            "Modules/PageTranslation/Content/style.css",
            "Modules/CourseManagement/content/style.css",
            "Modules/Yammer/Content/style.css",
            "Modules/Webform/Content/style.css",
            "Modules/Helpdesk/Content/style.css"
        ]
    }
];
var jsBundles = [
    {
        outFile: "./Base/Bundles/AdminScripts.js",
        src: [
            "Base/Scripts/ace/ace.js",
            "Base/Scripts/ace/ext-language_tools.js",
            "Base/Scripts/ace/mode-javascript.js",
            "Base/Scripts/ace/mode-html.js",
            "Base/Scripts/ace/theme-monokai.js",
            "Base/Scripts/ace/ext-language_tools",
           
        ]
    },
    {
        outFile: "./Base/Bundles/Scripts.js",
        src: [
            "Base/Scripts/jquery-getQueryParameters.js",
            "Base/Scripts/lodash-wizdom.js",
            "Base/Scripts/bootstrap.js",
            "Base/Scripts/angular-touch.js",
            "Base/Scripts/froala/angular-froala/src/froala-sanitize.js",
            "Base/Scripts/angular-tinymce.js",
            "Base/Scripts/angular-ace.js",
            "Base/Scripts/ace/mode-javascript.js",
            "Base/Scripts/ace/mode-html.js",
            "Base/Scripts/ace/theme-monokai.js",
            "Base/Scripts/ace/ext-language_tools",
            "Base/Scripts/angular-moment.js",
            "Base/Scripts/ui-bootstrap-tpls-0.12.0.js",
            "Base/Scripts/checklist-model.js",
            "Base/Scripts/sortable.js",
            "Base/Scripts/tinymce/tinymce.js",            
            "Base/Scripts/mentio.js",
            "Base/Scripts/angular-strap.js",
            "Base/Scripts/formly.js",
            "Base/Scripts/scrollbar/perfect-scrollbar.js",
            "Base/Scripts/scrollbar/jquery.mousewheel.js",
            "base/scripts/scrollbar/angular-perfect-scrollbar.js",
            "Base/Scripts/noty/jquery.noty.packaged.js",
            "Base/Scripts/Chart.js",
            "Base/Scripts/tc-angular-chartjs.js",
            //"Modules/Branding/Scripts/wizdom365Branding.js",
            //"Modules/Branding/Scripts/Wizdom365HandleOverflow.js",
            //"Modules/Branding/Scripts/wizdom365SPFix.js",
            "Base/Scripts/bootstrap-colorpicker-module.js",
            "Base/Scripts/angular-swagger/swagger-ui.js",
            "Base/Scripts/angular-tree-control/angular-tree-control.js",
            "Base/Scripts/angular-equalcolumns.js"
            //"Base/Scripts/element-resize-detector.js"
        ]
    }
];
var tsBundles = [
    {
        outFile: "./Base/Bundles/App.js",
        src: [
            './Modules/**/*.ts',
            //'./Base/**/*.ts',
            './Base/Scripts/typings/**/*.d.ts',
            '!/**/*.admin.ts',
            '!/**/*.editmode.ts'
        ]
    },
    {
        outFile: "./Base/Bundles/App.Admin.js",
        src: [
            './Modules/**/*.admin.ts',
            './Base/**/*.ts',
            './Base/Scripts/typings/**/*.d.ts'
        ]
    },
    {
        outFile: "./Base/Bundles/App.Editmode.js",
        src: [
            './Modules/**/*.editmode.ts',
            './Base/Scripts/typings/**/*.d.ts'
        ]
    }
];

gulp.task('xCompileSass', function () {
    var sassOptions = {
        //outputStyle: 'compressed'
        //relativeUrls : false
    };
    return gulp.src(sassFiles)
        .pipe(sass(sassOptions).on('error', sass.logError))
        .pipe(header('\ufeff'));/*.pipe(gulp.dest(function(file) {
            return file.base + "";
        }));*/
});
gulp.task('xBundleCss', ["xCompileSass"], function () {
    var tasks = [];
    function bundleCss(files, destFolder, destName, destMinName) {
        var cssFull = gulp.src(files)
            .pipe(cleanCss(
                {
                    relativeTo: destFolder,
                    format: 'beautify'
                }))
            .pipe(concat(destName))
            .pipe(gulp.dest(destFolder));
        var cssMin = gulp.src(files)
            .pipe(cleanCss(
            {
                relativeTo: destFolder,
                //format: 'beautify'
            }))
            .pipe(concat(destMinName));//.pipe(gulp.dest(destFolder));

        tasks.push(cssFull);
        tasks.push(cssMin);
    }

    for (var i = 0; i < cssBundles.length; i++) {
        var destFolder = cssBundles[i].outFile.substr(0, cssBundles[i].outFile.lastIndexOf("/"));
        var fileName = cssBundles[i].outFile.substr(cssBundles[i].outFile.lastIndexOf("/")+1);
        var minFile = fileName.substr(0, fileName.lastIndexOf(".")) + ".min.css";
        //gutil.log("destFolder: " + destFolder);
        //gutil.log("fileName: " + fileName);
        //gutil.log("minFile: " + minFile);
        bundleCss(cssBundles[i].src, destFolder, fileName, minFile);
    }
    return es.merge(tasks);
});
gulp.task('xCompileTs', function () {
    var tasks = [];
   
    for (var i = 0; i < tsBundles.length; i++) {
        var destFolder = tsBundles[i].outFile.substr(0, tsBundles[i].outFile.lastIndexOf("/"));
        var fileName = tsBundles[i].outFile.substr(tsBundles[i].outFile.lastIndexOf("/") + 1);

        var task = gulp.src(tsBundles[i].src)
                //.pipe(sourcemaps.init())
                .pipe(typescript({
                    sortOutput: true,
                    emitError: false,
                    noLibCheck: true,
                    removeComments: true
                }))
                .pipe(concat(fileName))
                //.pipe(sourcemaps.write('.', { sourceRoot: '/' }))
                //.pipe(gulpIgnore.exclude(["**/*.map"]))
                //.pipe(uglify())
                .pipe(gulpif(argv.release, uglify())) // only uglify if runing gulp like: "gulp --release"
            ;//.pipe(gulp.dest(destFolder));
        tasks.push(task);
    }
    return es.merge(tasks);
});
gulp.task('xBundleJs', function () {
    var tasks = [];
    function bundleJs(files, destFolder, destName, destMinName) {
        var cssFull = gulp.src(files)
            .pipe(concat(destName))
            .pipe(gulp.dest(destFolder));
        var cssMin = gulp.src(files)
            .pipe(uglify())
            .pipe(concat(destMinName));//.pipe(gulp.dest(destFolder));

        tasks.push(cssFull);
        tasks.push(cssMin);
        //return [cssFull, cssMin];
    }

    for (var i = 0; i < jsBundles.length; i++) {
        var destFolder = jsBundles[i].outFile.substr(0, jsBundles[i].outFile.lastIndexOf("/"));
        var fileName = jsBundles[i].outFile.substr(jsBundles[i].outFile.lastIndexOf("/") + 1);
        var minFile = fileName.substr(0, fileName.lastIndexOf(".")) + ".min.js";
        //gutil.log("destFolder: " + destFolder);
        //gutil.log("fileName: " + fileName);
        //gutil.log("minFile: " + minFile);
        bundleJs(jsBundles[i].src, destFolder, fileName, minFile);
    }
    return es.merge(tasks);
});


gulp.task('xWatch', function () {
    livereload.listen();
    // sass files
    //gulp.watch(sassFiles, ['xBundleCss']);

    // ts files
    gulp.watch(['Modules/**/*.ts', 'Base/**/*.ts'], ['xCompileTs']);

    // css files
    //for (var i = 0; i < cssBundles.length; i++)
    //    gulp.watch(cssBundles[i].src, ['xBundleCss']);

    // js files
    for (var i = 0; i < jsBundles.length; i++)
        gulp.watch(jsBundles[i].src, ['xBundleJs']);


    // live reload
    //var reloadSrc = [
    //    'Modules/**/*.html',
    //    "./Base/Bundles/App.Editmode.js",
    //    "./Base/Bundles/App.Admin.js",
    //    "./Base/Bundles/App.js",
    //    //"./Base/Bundles/StylesModules.css"
    //];
    //gulp.watch(reloadSrc, function (input) {
    //    if (input.type == "changed") {
    //        gutil.log(input);
    //        livereload.changed("dummy.html");
    //    }
    //});
});