'use strict';
var Cube = require('node-cube');
var path = require('path');
var fs = require('xfs');
const userConfig = require('../../config/user');
const sysConfig = require('../../config');
const logged = userConfig.loggedin;
const user = logged && userConfig[userConfig.loggedin];

//重写cube log
let LOG = {
  warn: function () {},
  info: function () {},
};

let methods = ['debug', 'error'];

function log(type, args) {
  args = [].slice.call(args);
  args.unshift(type);
  args.unshift('[CUBE]');
  console.log.apply(console, args);
}


methods.forEach( (method) => {
  LOG[method] = function () {
    log('[' + method.toUpperCase() + ']', arguments);
  };
});

exports.cubeAdmin = function (root, config) {
  return Cube.middleware({
    root: path.join(root, '/static/'),
    noDist: true,
    resBase: '/static/',
    middleware: true,
    remote: 'static',
    log: LOG,
    passUnknowExt: true,
    debug: config.debug,
    maxAge: 0//3600 * 48 * 1000
  })
}

exports.cubeUser = function (source) {
  var datavBase = path.join(source, '/datav_modules/');
  let cube = new Cube({
    root: source,
    middleware: true,
    passUnknowExt: true,
    log: LOG,
    processors: {
      '.less': 'cube-less',
      '.jsx': ['cube-react'],
      '.glsl': [['cube-glsl', {
      }]],
      ".js": [
        [
          "cube-lazy-parse",
          {
            "match": "\\.packed\\.js$"
          }
        ],
        [
          "cube-babel",
          {
            "presets": [
              [
                "react"
              ],
              [
                "env",
                {
                  "targets": {
                    "browsers": [
                      "last 2 versions",
                      "chrome >= 56"
                    ]
                  }
                }
              ]
            ],
            "plugins": [
              "transform-class-properties",
              "transform-es2015-spread",
              "transform-object-rest-spread"
            ]
          }
        ]
      ]
    },
    remoteBase: {
      'datav' : (user && user.server || sysConfig.serverDefault) + 'cube/'
    },
    debug: true,
    maxAge: 3600 * 48 * 1000
  });

  let originResolveModulePath = cube.resolveModulePath;

  cube.resolveModulePath = function (data, file, callback) {
    var deal = false;
    if (/^\w+?:/.test(file)){
      var afile = file.replace(/\/\d+\.\d+\.\d+[^\/]*/, '');
      var _file = afile.split('datav:/com');
      var _path = path.join(datavBase, _file[1]);
      if (!path.extname(_path)) {
        if (fs.existsSync(_path+'.js')) {
          deal = true;
        } else if (fs.existsSync(path.join(_path, 'index.js'))) {
          deal = true;
        }
      }
      if (fs.existsSync(_path)) {
        deal = true;
      }
    }
    let p = file;
    if (deal) p = path.join('/datav_modules', _path.replace(datavBase, ''));
    originResolveModulePath.call(this, data, p, callback);
  }
  return Cube.middleware(cube, {});
}