/**
 * Created by chen on 2017/7/17.
 */


import BaseController from "../../common/base/base_controller";
const projectModel = require("../../pm/models/project_model");
const pmFacade = require('../../pm/facade/pm_facade');
import OptionsDao from '../../options/models/optionsModel';
import optionSetting from '../../options/models/optionTypes';
let config = require("../../../config/config.js");
module.exports =function (app) {
    const baseController = new BaseController();
    app.get('/main', baseController.init, function(req, res) {
        let pm = require('../../pm/controllers/pm_controller');
        const projectID = +req.query.project;
        pm.checkProjectRight(req.session.sessionUser.id, projectID, async function (hasRight, projectData, isOpenShareProject, allowCooperate) {
            if (hasRight) {
                //分享的项目，只读、协作（允许编辑）
                let projectReadOnly = false,
                    projectCooperate = false;
                if(req.session.sessionUser.id !== projectData.userID){
                    projectData._doc.readOnly = true;
                    projectCooperate = allowCooperate;
                    //允许协作的项目允许编辑，非只读
                    projectReadOnly = !projectCooperate;
                }
                let optionsDao = new OptionsDao();
                let options = await optionsDao.getOptions(req.session.sessionUser.id, req.session.sessionCompilation._id);
                if(options){
                    options = await optionsDao.saveOptions(req.session.sessionUser.id, req.session.sessionCompilation._id, optionSetting);
                }
                const markReadProjectIDs = isOpenShareProject ? await pmFacade.markShareItemsRead(projectID, req.session.sessionUser.id) : [];
                res.render('building_saas/main/html/main.html',
                    {
                        userAccount: req.session.userAccount,
                        userID: req.session.sessionUser.id,
                        projectData: projectData,
                        compilationName: req.session.sessionCompilation.name,
                        versionName: req.session.compilationVersion,
                        projectReadOnly: projectReadOnly,
                        projectCooperate: projectCooperate,
                        LicenseKey:config.getLicenseKey(process.env.NODE_ENV),
                        options:JSON.stringify(options),
                        overWriteUrl:req.session.sessionCompilation.overWriteUrl,
                        markReadProjectIDs: JSON.stringify(markReadProjectIDs)
                    });
            } else {
                res.redirect('/pm');
            }
        });
    });
}
