var gulp=require('gulp'),
    fs=require('fs'),
    path=require('path'),

    gutil = require('gulp-util'),
    ftp = require('gulp-ftp'),

    plumber = require('gulp-plumber'),
    sass = require('gulp-sass'),
    csso = require('gulp-csso'),

    autoprefixer = require('gulp-autoprefixer'),
    rename = require("gulp-rename"),
    clean = require('gulp-clean'),

    server = require('gulp-develop-server'),

    rev=require("gulp-rev"),
    revCollector=require("gulp-rev-collector"),
    webpack = require('webpack');

var Glob = require("glob");
var mapStream = require('map-stream');
var vfs = require('vinyl-fs');



var config = JSON.parse(fs.readFileSync('./package.json').toString());

/*获取项目名称*/
var dist={
    name:"../dist",
    static:"../dist/"+ config.name + "/"+ config.version,
    code:"../server"
};

/*CDN 上传*/
var ftpConfig = {
    host: '218.94.75.58',
    user: 'php',
    pass: 'yoho9646'
};

/*清楚开发目录*/
gulp.task("clean",function(){
    return gulp.src(dist.name,{read:false})
    .pipe(clean());
});

gulp.task('dist', function() {
    var ftpstream = ftp(ftpConfig);
    return gulp.src(dist.static+'/**/')
        .pipe(ftpstream)
        .pipe(gutil.noop());
});

/*sass*/
gulp.task("sass",function(){
    return gulp.src("static/sass/index.scss")
    .pipe(plumber())
    .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
    .pipe(csso())
    .pipe(rename(function(path){
        path.basename+=".min";
        path.extname=".css";
    }))
    // .pipe(rev())
    .pipe(gulp.dest(dist.static))
    // .pipe(rev.manifest())
    // .pipe(gulp.dest("./config/css"));
});

/*assets*/
gulp.task("assets", function () {
    gulp.src('static/assets/**')
        .pipe(gulp.dest(path.join(dist.static, "assets")));
});

/*rev*/
gulp.task("rev",function(){
    return gulp.src(["./config/css/*.json","./apps/common/views/__ui/header.html"])
    .pipe(revCollector({replaceReved: true}))
    .pipe(gulp.dest("./apps/common/views/__ui/"));
});

/**/
gulp.task("jquery", function (cb){
    var JQconfig = require('./webpack.config.dev');
    JQconfig.output.path=path.join(dist.static,"jquery");
    webpack(JQconfig, cb);
});

gulp.task("static", function () {
    gulp.watch('static/sass/**/*.scss', ['sass']);
    gulp.watch('static/js.jquery/**/*.js', ['jquery']);
});


//发布到CDN
gulp.task('dist', function () {
    var ftpstream = ftp(ftpConfig);
    return gulp.src('../dist/**/')
        .pipe(ftpstream)
        .pipe(gutil.noop());
});
//启动服务
gulp.task('server', function () {
    server.listen({
        path:'index.js'
    });
    gulp.watch([
        'index.js',
        "./apps/**/controllers/*.js",
        "./apps/**/interfaces/*.js",
        "./apps/**/views/**.html"
    ], server.restart);

});





/**************************************************************
* 服务器打包
**************************************************************/
gulp.task("mvc", ["controllers","interfaces","view","framework"]);

gulp.task("controllers", function () {
    vfs.src("./apps/**/controllers/*.js").pipe(mapStream(function(file,callback){
        file.path=file.path.replace(/apps\\([^/]+)\\controllers\\([^.]+).js/g, function($0,$1,$2){
            return ["controllers",$1+"."+$2+".js"].join(path.sep);
        });
        callback(null,file);
    })).pipe(vfs.dest(path.join(dist.code, "controllers")));
});
gulp.task("interfaces", function () {
    vfs.src("./apps/**/interfaces/*.js").pipe(mapStream(function(file,callback){
        file.path=file.path.replace(/apps\\([^/]+)\\interfaces\\([^.]+).js/g, function($0,$1,$2){
            return ["interfaces",$1+"."+$2+".js"].join(path.sep);
        });
        callback(null,file);
    })).pipe(vfs.dest(path.join(dist.code, "interfaces")));

});
gulp.task('view', function () {
    
    var log = function (file, cb) {
        var src=file.path.replace(/\\/g, '\/');
        var arr = src.match(/apps\/([^/]+)\/views\/(.+)/, "g");
        file.path = "views/"+arr[1] + '/' + arr[2];
        if(file.contents){
            var contents=file.contents.toString();
            contents=contents.replace(/((?:\.\.\/)+)([^/]+)\/views\/([^'"]+)/g,function($0,$1,$2,$3){
                return $1.replace(/\.\.\//,'')+[$2,$3].join('/');
            });
            file.contents=new Buffer(contents);
        }
        cb(null, file);
    };
    vfs.src("./apps/**/views/**/*")
        //.pipe(rev())//这里您可以做一些pipe的操作
        .pipe(mapStream(log))
        .pipe(vfs.dest(path.join(dist.code, "views"))); //这里会多输出一次
    
    //gulp.start(['clean']); //我们需要执行一次clean 清理了多余的那层目录
});
gulp.task('framework', function () {
    gulp.src('mid/**').pipe(gulp.dest(path.join(dist.code, "mid")));
    gulp.src('libs/**').pipe(gulp.dest(path.join(dist.code, "libs")));
    gulp.src(['filters.js','index.js']).pipe(gulp.dest(dist.code));
    gulp.src('package.json').pipe(mapStream(function(file, cb){
        var contents=JSON.parse(file.contents.toString());
        delete contents.devDependencies;
        file.contents=new Buffer(JSON.stringify(contents));
        cb(null,file);
    })).pipe(gulp.dest(dist.code));
});



/**************************************************************
* Vue打包
**************************************************************/
var vueConfig = require('./webpack.config.vue');

var vueCompiler=function(entry){
    var entry = entry||{};
    Glob.sync("./apps/**/client/**/index.js").forEach(function (src) {
        var arr = src.match(/apps\/([^/]+)\/client\/([^.]+).index.js/, "g");
        var name = arr[1] + "." + arr[2];
        entry[name] = src;
    });
    return entry;
}
gulp.task("vue-gulp", function (cb) {
    
    vueConfig.entry = vueCompiler({
        'libs':["jquery","vue","./static/js.vue/index.js"]
    });
    vueConfig.output= {
        path: path.join(dist.static, "vue"),
        filename: "[name].js"
    }
    webpack(vueConfig, cb);
});

gulp.task('vue',["vue-gulp"], function (cb) {
    gulp.watch([
        "./apps/**/client/**/*.*",
        "./components/**/*.*"
    ], function(item){
        var entry={};
        if(/components/g.test(item.path)){
            gulp.run("vue-gulp");
        }else{
            item.path=item.path.split(path.sep);
            var changeFileName=item.path[item.path.length-1];
            item.path[item.path.length-1]="index.js";
            var src=item.path.join('/');
            console.log("filename:"+changeFileName+": change and src:"+src);
            var arr = src.match(/apps\/([^/]+)\/client\/([^.]+).index.js/, "g");
            var name = arr[1] + "." + arr[2];
            entry[name] = src;
            vueConfig.entry=entry;
            vueConfig.output= {
                path: path.join(dist.static, "vue"),
                filename: "[name].js"
            }
            webpack(vueConfig, cb);
        }
       
    });
});

gulp.task("default",["jquery","assets","sass","vue-gulp"]);
gulp.task('start', ["default", "static", "server","vue"]);//"vue"