var Middleware = require('zfinder-middleware');
var Route = require('zfinder-route');
var fsExtraPromise = require('fs-extra-promise');
var htmlUtils = require('zero-text/html');
var json = require('zero-encoding/json');
var lang = require('zero-lang');
var path = require('path');
var sprintf = require('zero-fmt/sprintf');
var templateEngine = require('zero-text/template');
var zfinderUtils = require('zfinder-utils');

var defaultConfig = zfinderUtils.loadYamlConfig(path.resolve(__dirname, '../config.yaml'));

var mw = new Middleware()
    .addRoute(new Route({
        // properties
        name: '',
        method: 'get', // all|get|post|put|delete|options
        url: '*',
        priority: 1,

        // methods
        serve: function (options, config) {
            options = lang.extend({}, defaultConfig, options);
            var theme;
            var root = config.root;

            // fill properties
            var me = this;
            me.priority = options.priority;
            me.name = sprintf('%s:%s', options.name, me.method);

            if (options.theme) {
                theme = mw.theme = isAbsolute(options.theme) ?
                    options.theme : path.resolve(process.cwd(), options.theme);
            } else {
                theme = path.resolve(__dirname, '../theme');
            }
            var htmlRender = templateEngine.compile(
                fsExtraPromise.readFileSync(path.join(theme, './src/template/index.html'), 'utf8')
            );

            // your code goes here
            return function (req, res, next) {
                // not applying for this middleware
                if (req._mw && req._mw !== options.name) {
                    return next();
                }

                var pathname = req._normalizedPathname;
                var ext = path.extname(pathname);
                if ((ext !== '.xmind') || (req._query && lang.hasKey(req._query, 'raw'))) {
                    return next();
                }

                if (fsExtraPromise.existsSync(pathname)) {
                    var c = {
                        middleware: lang.extend({
                            pathname: pathname,
                            root: sprintf('%s/%s', config.path.middlewareRoot, options.name)
                        }, options),
                        zfinder: config
                    };
                    var data = htmlRender({
                        content: fsExtraPromise.readFileSync(pathname, 'utf8'),
                        middleware: c.middleware,
                        zfinder: c.zfinder,
                        jsonData: zfinderUtils.fixWindowsPath(json.stringify(c))
                    }, lang.extend({}, htmlUtils, lang));
                    res._HTMLRes(data);
                } else {
                    return next();
                }
            };
        },
    }));

module.exports = mw;

