/**
 * app.js
 * Copyright (c) 2000 - 2017 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Contact:
 * Sungmin Kim <sm.art.kim@samsung.com>
 * Jonghwan Park <iwin100.park@samsung.com>
 * Kitae Kim <kt920.kim@samsung.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributors:
 * - S-Core Co., Ltd
**/

var path = require('path');
var async = require('async');
var expressio = require('express.io');
var _ = require('underscore');

var dibs = require('../../../core/dibs.js');
var utils = require('../../../lib/utils.js');
var dfs = require('../../../plugins/dibs.dist-fs/dist-fs.js');
var FileSystem = require('../../dibs.core/filesystem.js');

var router = new expressio.Router();
module.exports.router = router;


router.post('/upload', function (req, res) {
    var files = req.files;
    var downloadedPath;
    var fileName;
    if (_.isArray(files.uploadedfiles)) {
        downloadedPath = files.uploadedfiles[0].path;
        fileName = req.files.uploadedfiles[0].name;
    } else {
        downloadedPath = files.uploadedfiles.path;
        fileName = files.uploadedfiles.name;
    }

    var newPath = path.join(path.dirname(downloadedPath), fileName);
    async.waterfall([
        function (cb) {
            // remove target file if it exists
            utils.removePathIfExist(newPath, function (err) {
                cb(err);
            });
        },
        function (cb) {
            FileSystem.move(downloadedPath, newPath, cb);
        },
        function (cb) {
            // move file to repository server
            dfs.addFile(null, newPath, {
                lifetime: 60 * 60 * 1000
            }, cb);
        },
        function (dfsPath, cb) {
            // clean up uploaded files
            utils.removePathIfExist(newPath, function (err) {
                cb(err, dfsPath);
            });
        }
    ],
    function (err, dfsPath) {
        if (err) {
            dibs.log.error(JSON.stringify(err));
            res.status(503).send(JSON.stringify(err.message));
        } else {
            res.send(JSON.stringify({
                path: dfsPath
            }));
        }
    });
});
