/**
 * Created by Gifer on 20.03.2017.
 */

var fs         = require('fs');
var Service    = require('./service.js');
var console    = require('gifer-console');
var URL        = require('url');

exports.do = function (req, res) {
    var file         = null;
    var path         = null;
    var downloadFile = null;
    var kanbanForum  = "";
    var checkUpdate  = false;
    var rootPath     = "";

    try {
        file = URL.parse(req.url).pathname.split('.');
        path = Service.ExtractPath(req.url).split('/');

        kanbanForum = path[2] === "kanban" || path[2] === "forum" ? path[2] + "/" : "";
        checkUpdate = path[2] === "updates";
    } catch (e) {}

    if (file && path) {
        if (path.length === 2 || kanbanForum) {
            downloadFile = Service.ExtractFileName(req.url);
        } else
        if (checkUpdate){
            downloadFile = file;
        } else {
            downloadFile = path[path.length - 1] + "." + file[file.length - 1];
        }

        rootPath = checkUpdate ? MCPathes.Updates : MCPathes.Files + kanbanForum;

        fs.stat(rootPath + downloadFile, function (err, stat) {
            if (err) {
                res.writeHead(404);
            } else {
                res.writeHead(200, { 'Content-Length': stat.size });
            }

            res.end();
        });
    } else {
        res.writeHead(404);
        res.end();
    }
};