/**
 * @fileOverview Melody coder 文章的发布器，包括了对文章的读取，分析，以及最后的发布一套流程
 * @author <a href="mailto:xukai.ken@gmail.com">(XU Kai)xukai.ken@gmail.com</a>
 * @version 0.1
 *
 */

var fs = require('fs'), http = require('http'), log = require('./logger'), config = require('../config').config;
parser = require('./parser');

var Logger = log.Logger;

var Publisher = function(opts) {
	this.opts = opts || {};
	this.init();
};

var pFn = Publisher.prototype;

// 初始化
pFn.init = function() {
	var articles = [], isSuccess = false;

	// 查找统计目录中扩展名为.json的文件
	var files = fs.readdirSync('./');
	for (var j = 0; j < files.length; j++) {
		var fName = files[j];
		var extName = fName.split('.').pop();
		if (extName == 'json') {
			articles.push({
				title : fName
			});
		}
	}

	// 分析该文件的结构是否合法
	for (var j = 0; j < articles.length; j++) {
		var article = articles[j];

		try {
			var content = fs.readFileSync('./' + article.title);
			Logger.log('Read the content from article ' + article.title + ' .');

			var Parser;
			if (this.opts.parser)
				Parser = this.opts.parser
			var hook = Parser.parse(content);
			if (hook)
				for (var i in hook)
				article[i] = hook[i];
		} catch (e) {
			Logger.log('Error getting the content for the file .');
		}
	}
	this.publish(articles, function() {
		Logger.log('Publish the article successfully !');
	});
};

// 发布文章
pFn.publish = function(articles, callback) {
	var send = function(article, index) {
		var reqData = 'r=' + encodeURIComponent(JSON.stringify(article));

		// 发送文章到服务器
		var options = {
			hostname : config.site.SITE_BASE_URL,
			port : 80,
			path : config.site.ARTICLE_PUBLISH_URL,
			method : 'POST',
			headers : {
				'Content-Type' : 'application/x-www-form-urlencoded',
				'Content-Length' : reqData.length
			}
		}

		Logger.log('Request the interface form server side .');
		var req = http.request(options, function(resp) {
			if (resp.statusCode == 200) {
				resp.on('data', function(chunk) {
					chunk = JSON.parse(chunk);
					if (chunk.status.code == 1) { 
						callback();
					} else {
						Logger.error(chunk.status.content);
					}
				});
			}
		});
		req.on('error', function(e) {
			Logger.log('Problem with request: ' + e.message);
		});

		// 写数据
		req.write(reqData);
		req.end();
	};
	articles.forEach(send);
};

var Parser = parser.Parser;
new Publisher({
	parser : new Parser('BASIC')
});


@@ -1612,33 +1612,19 @@
 e : 
-config.site.SITE_BASE_URL
+'127.0.0.1'
 ,%0D%0A%09
@@ -1636,9 +1636,11 @@
 t : 
-8
+300
 0,%0D%0A
@@ -1816,16 +1816,128 @@
 a.length
+,%0D%0A%09%09%09%09%0D%0A%09%09%09%09'Cookie': 'connect.sid=s%253AoXtnURTxIo8ck-X5evTJHgh9.iiCiwnRzxsluJCt9OMIHTYMVch2%252B8CXU1mUUS%252BdQQY'
 %0D%0A%09%09%09%7D%0D%0A

Modify cookie to publish the post.