'use strict';

const _ = require('lodash');
const SystemMetaService = require('../../../../services/systemMetaService');
const SessionService = require('../../../../services/sessionService');

const selectSystem = (req, res) => {
    const stationId = req.body.stationId || null;
    const sessionId = req.header('x-forwarded-for') || _.get(req, 'connection.remoteAddress') || 'localhost';

    const selectedSystem = SystemMetaService.select(stationId);
    if (!_.has(selectedSystem, 'stationId')) {
        return res.status(500).json({ error: 'Invalid "stationId" parameter' });
    }

    // Grab the division ID from the associated station ID via service, then inject them into the session
    SystemMetaService.lookupKernelSystemParameters({ stationId: selectedSystem.stationId }, (err, ksp) => {
        if (err) {
            return res.status(500).json({ error: `Invalid kernel parameters for station "${stationId}"` });
        }

        const sessionUpdate = {
            stationId: selectedSystem.stationId,
            divisionId: ksp.defaultInstitution.id,
            divisionLabel: ksp.defaultInstitution.label,
        };
        SessionService.update(sessionId, sessionUpdate);

        const result = _.extend({}, selectedSystem, sessionUpdate);
        return res.json(result);
    });
};

module.exports = [{
    method: 'POST',
    path: '/',
    callback: selectSystem,
}];
