/**
 * approval.js
 * Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Contact:
 * DongHee Yang <donghee.yang@samsung.com>
 * Sungmin Kim <sm.art.kim@samsung.com>
 * Jiil Hyoun <jiil.hyoun@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 async = require('async');
var expressio = require('express.io');
var session = require('./session');
var dibs = require('../../../core/dibs.js');
var DError = require('../../../core/exception.js');

var router = new expressio.Router();

module.exports.router = router;

router.get('/approvals', session.checkSession, function (req, res) {

    var email = req.session.email;
    var options;

    async.waterfall([
        function (cb) {
            session.isAdmin(email, cb);
        },
        function (isAdmin, cb) {
            if (isAdmin) {
                options = {};
                cb(null);
            } else {
                options = {
                    email: email,
                    includeRoutes: true
                };
                if (req.query.id) {
                    options.id = req.query.id;
                }
                if (req.query.subject) {
                    options.subject = req.query.subject;
                }
                if (req.query.contents) {
                    options.contents = req.query.contents;
                }
                if (req.query.submmissionStatus) {
                    options.submmissionStatus = req.query.submmissionStatus;
                }
                if (req.query.submmissionDate) {
                    options.submmissionDate = req.query.submmissionDate;
                }
                if (req.query.summary) {
                    options.summary = req.query.summary;
                }
                if (req.query.type) {
                    options.type = req.query.type;
                }
                cb(null);
            }
        },
        function (cb) {
            dibs.rpc.approvalmgr.searchApprovals(options, function (err, approvals) {
                if (err) {
                    dibs.log.error(JSON.stringify(err));
                    res.status(503).send(JSON.stringify(err.message));
                    cb(err);
                } else {
                    res.send(approvals.sort(function (a, b) {
                        if (a.id < b.id) {
                            return 1;
                        }
                        if (a.id > b.id) {
                            return -1;
                        }
                        return 0;
                    }));
                    cb(null);
                }
            });
        }], function (err) {
        if (err) {
            dibs.log.error(JSON.stringify(err));
        }
    });
});


router.get('/approvals/:id', session.checkSession, function (req, res) {
    var approvalId = req.param('id');
    var cond = {
        id: approvalId
    };
    if (approvalId === undefined) {
        res.status(503).send('approval id is undefined!');
        return;
    }

    dibs.rpc.approvalmgr.searchApprovals(cond, function (err, approvals) {
        if (err) {
            dibs.log.error(JSON.stringify(err));
            res.status(503).send(JSON.stringify(err.message));
        } else if (!approvals || approvals.length <= 0) {
            var error = new DError('WEB001', {
                arguments: 'approval ID: ' + approvalId
            });
            dibs.log.error(JSON.stringify(error));
            res.status(503).send(JSON.stringify(error.message));
        } else {
            var approval = approvals[0];
            res.send(approval);
        }
    });
});



// TODO add approval -> not in spec now but shoud do this any time
//router.post('/approvals', session.checkSession, function (req, res) {
//dibs.rpc.approvalmgr.addApproval(email, subject, contents, summary, approvalRoutes, type, callback);
//});

// TODO modify approval -> not in spec now but shoud do this any time
//router.put('/approvals', session.checkSession, function (req, res) {
//dibs.rpc.approvalmgr.modifyApproval(approval, eventType, callback);
//});

router.put('/approvals/cancel', session.checkSession, function (req, res) {
    var email = req.session.email;
    var approvalId = req.body.id;
    var message = req.body.message;

    if (approvalId === undefined) {
        res.status(503).send('approval id is undefined!');
        return;
    }

    if (message === undefined) {
        res.status(503).send('approval message is undefined!');
        return;
    }

    dibs.rpc.approvalmgr.cancel(approvalId, email, message,
        function (err) {
            if (err) {
                dibs.log.error(err);
                res.status(503).send(JSON.stringify(err.message));
            } else {
                res.send();
            }
        });
});

router.put('/approvals/approve', session.checkSession, function (req, res) {
    var email = req.session.email;
    var approvalId = req.body.id;
    var message = req.body.message;

    if (approvalId === undefined) {
        res.status(503).send('approval id is undefined!');
        return;
    }

    if (message === undefined) {
        res.status(503).send('approval message is undefined!');
        return;
    }

    dibs.rpc.approvalmgr.approve(approvalId, email, message,
        function (err) {
            if (err) {
                dibs.log.error(err);
                res.status(503).send(JSON.stringify(err.message));
            } else {
                res.send();
            }
        });
});

router.put('/approvals/reject', session.checkSession, function (req, res) {
    var email = req.session.email;
    var approvalId = req.body.id;
    var message = req.body.message;

    if (approvalId === undefined) {
        res.status(503).send('approval id is undefined!');
        return;
    }

    if (message === undefined) {
        res.status(503).send('approval message is undefined!');
        return;
    }

    dibs.rpc.approvalmgr.reject(approvalId, email, message,
        function (err) {
            if (err) {
                dibs.log.error(err);
                res.status(503).send(JSON.stringify(err.message));
            } else {
                res.send();
            }
        });
});
// approval delete is not support in spec
//router.delete('/approvals', session.checkSession, function (req, res) {
//});
