// 为了显示图片
// leanote://api/file/getImage?fileId=xxx
// 
// 
// 没用!!! 因为protocal不支持异步
// https://github.com/atom/electron/issues/410

var protocol = require('protocol');

var Evt = require('evt');
var Common = require('common');
var File = require('file');
var Api = require('api');
var db = require('db');

var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');

var Server = {
	mime: {
	    "css": "text/css",
	    "gif": "image/gif",
	    "html": "text/html",
	    "ico": "image/x-icon",
	    "jpeg": "image/jpeg",
	    "jpg": "image/jpeg",
	    "js": "text/javascript",
	    "json": "application/json",
	    "pdf": "application/pdf",
	    "png": "image/png",
	    "svg": "image/svg+xml",
	    "swf": "application/x-shockwave-flash",
	    "tiff": "image/tiff",
	    "txt": "text/plain",
	    "wav": "audio/x-wav",
	    "wma": "audio/x-ms-wma",
	    "wmv": "video/x-ms-wmv",
	    "xml": "text/xml"
	},
	router: function(request) {
		var me = this;

		var pathname = url.parse(request.url).pathname;
		while(pathname[0] == '/') {
	    	pathname = pathname.substr(1);
	    }

	    if(pathname == 'api/file/getImage') {
	    	return me.getImage(request, response);
	    } else {
	    	response.end();
	    	return false;
	    }
	},

	e404: function(res) {
		var me = this;
		res.writeHead(404, {
            'Content-Type': 'text/plain'
        });
        res.write("This request URL "  +  me._req.url + " was not found on this server.");
        res.end();
	},

	// 返回图片
	retImage: function(filePath, res) { 
		var me = this;
		var ext = path.extname(filePath);
		ext = ext ? ext.slice(1) : 'unknown';
		filePath = filePath + '';
		fs.readFile(filePath, "binary", function (err, file) {
            if (err) {
                res.writeHead(500, {
                    'Content-Type': 'text/plain'
                });
                res.end();
            } else {
                var contentType = me.mime[ext] || "text/plain";
				res.writeHead(200, {'Content-Type': contentType});
				res.write(file, "binary");
				res.end();
            }
        });
	},

	getImage: function(req, res) { 
		var me = this;
		// fileId
		var fileId = url.parse(req.url, true).query['fileId'];
		if(!fileId) {
			return me.e404(res);
		}
		File.getImage(fileId, function(fileLocalPath) {
			if(path) {
				return me.retImage(fileLocalPath, res);
			} else {
				return me.e404(res);
			}
		})
	}
};


protocol.registerProtocol('leanote', function(request) {
  var url = request.url.substr(7);
  return new protocol.RequestFileJob(path.normalize(__dirname + '/' + url));
});