var express = require('express');
var router = express.Router();
var pgp = require('pg-promise')();

let pgUser = 'postgres';
let pgPass = 'postgres';
let pgHost = 'localhost';
let pgPort = 5432
let pgDatabase = 'comt';

if (process.env.POSTGRES_HOST) {
  pgHost = process.env.POSTGRES_HOST;
}

if (process.env.POSTGRES_PORT) {
  pgPort = process.env.POSTGRES_PORT;
}

if (process.env.POSTGRES_USER) {
  pgUser = process.env.POSTGRES_USER;
}

if (process.env.POSTGRES_PASSWORD) {
  pgPass = process.env.POSTGRES_PASSWORD;
}

if (process.env.POSTGRES_DB) {
  pgDatabase = process.env.POSTGRES_DB;
}

var db = pgp(`postgres://${pgUser}:${pgPass}@${pgHost}:${pgPort}/${pgDatabase}`);

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'The U.S. Integrated Ocean Observing System (IOOS)' });
});

/* GET region map page. */
router.get('/regions', function(req, res, next) {
  res.render('regions', { title: 'The U.S. Integrated Ocean Observing System (IOOS) | Regions Map' });
});

/* GET contact us page. */
router.get('/contact-us', function(req, res, next) {
  res.render('contact-us', { title: 'The U.S. Integrated Ocean Observing System (IOOS) | Contact Us' });
});

/* GET comt about page. */
router.get('/comt', function(req, res, next) {
  db.many('SELECT title, SUBSTRING (overview, 0, 280) as overview FROM projects ORDER BY id ASC', [true])
  .then(function (data) {
    res.render('comt/index', {
      title: 'The U.S. Integrated Ocean Observing System (IOOS) | Coastal and Ocean Modeling Testbed Projects',
      projects: data });
  })
  .catch(function (error) {
    console.log('ERROR:', error);
  });
});

/* GET comt projects page. */
router.get('/comt/projects/:project', function(req, res, next) {
  var projectTitle = req.params.project.replace(/-/g, '');
  var allDatasets = require('../public/comt_datasets');
  var projectDatasets = [];
  db.task(function(t){
    return t.batch([
      t.many('SELECT title FROM projects ORDER BY id ASC', [true]),
      t.one('SELECT id, title, team as "Project Team", overview as "Project Overview and Results", ' +
              'model_desc as "Model Descriptions", sub_project_desc as "Sub-Project Descriptions", ' +
              'pubs as "Publications", title_key FROM projects WHERE regexp_replace(LOWER(title), \'[\.\/\\s+]\', \'\', \'g\') = \'' + projectTitle + '\'', [true])
    ]);
  })
  .then(function (data) {
    allDatasets.dataset.forEach(function (dataset) {
      if (dataset.comt.project === data[1].title_key)
        projectDatasets.push(dataset);
    });
    res.render('comt/project', {
      title: 'The U.S. Integrated Ocean Observing System (IOOS) | Coastal and Ocean Modeling Testbed Projects | ' + data[1].title,
      data: data,
      projectTitle: projectTitle,
      datasets: projectDatasets,
      path: req.path
    });
  })
  .catch(function (error) {
    console.log('ERROR:', error);
  });
});

/* GET comt dataset page. */
router.get('/comt/projects/:project/:dataset', function(req, res, next) {
  var datasetTitle = req.params.dataset,
      datasets = require('../public/comt_datasets'),
      variables = {},
      dataset = {},
      projectTitle = req.params.project.replace(/-/g, '');
  datasets.dataset.every(function (e, i) {
    if (e.title.replace(/[^\w]/g, '-').toLowerCase() === datasetTitle) {
      dataset = e;
      return false;
    }
    else
      return true;
  });
  if (dataset.variablesColored === undefined) {
    variables = require('../public/variables')
    for (var i=0; i<dataset.variablesMeasured.length;i++) {
      variables.variables.every(function (variableWithColor) {
        if (variableWithColor[1] !== '#000000' && variableWithColor[0] === dataset.variablesMeasured[i]) {
          dataset.variablesMeasured[i] = variableWithColor;
          return false;
        }
        else
          return true;
      });
    }
    dataset.variablesColored = true;
  }
  db.one('SELECT title FROM projects WHERE regexp_replace(LOWER(title), \'[\.\/\\s+]\', \'\', \'g\') = \'' + projectTitle + '\'', [true])
    .then(function (project) {
      res.render('comt/dataset', {
        title: 'The U.S. Integrated Ocean Observing System (IOOS) | Coastal and Ocean Modeling Testbed Projects | ' + project.title + ' | Datasets',
        dataset: dataset,
        project: project,
        projectPath: req.params.project,
        subProjectTitle: req.query.t
      });
    })
    .catch(function (error) {
      console.log('ERROR:', error);
  });
});

module.exports = router;

@@ -1,12 +1,25 @@
+%22use strict%22%0A
 var express 
@@ -111,320 +111,47 @@
 );%0A%0A
-let pgUser = 'postgres';%0Alet pgPass = 'postgres';%0Alet pgHost = 'localhost';%0Alet pgPort = 5432%0Alet pgDatabase = 'comt';%0A%0Aif (process.env.POSTGRES_HOST) %7B%0A  pgHost = process.env.POSTGRES_HOST;%0A%7D%0A%0Aif (process.env.POSTGRES_PORT) %7B%0A  pgPort = process.env.POSTGRES_PORT;%0A%7D%0A%0Aif (process.env.POSTGRES_USER) %7B%0A  pgUser = 
+const connectionstring = %60postgres://$%7B
 proc
@@ -171,25 +171,20 @@
 RES_USER
-;%0A%7D%0A%0Aif (
+%7D:$%7B
 process.
@@ -208,23 +208,12 @@
 WORD
-) %7B%0A  pgPass = 
+%7D@$%7B
 proc
@@ -233,25 +233,16 @@
 RES_
-PASSWORD;%0A%7D%0A%0Aif (
+HOST%7D:$%7B
 proc
@@ -262,29 +262,16 @@
 RES_
-DB) %7B%0A  pgDatabase = 
+PORT%7D/$%7B
 proc
@@ -293,93 +293,10 @@
 S_DB
-;%0A%7D%0A%0Avar db = pgp(%60postgres://$%7BpgUser%7D:$%7BpgPass%7D@$%7BpgHost%7D:$%7BpgPort%7D/$%7BpgDatabase%7D%60)
+%7D%60
 ;%0A%0A/
@@ -899,16 +899,49 @@
 next) %7B%0A
+%09var db = pgp(connectionstring);%0A
   db.man
@@ -1401,24 +1401,57 @@
 es, next) %7B%0A
+%09var db = pgp(connectionstring);%0A
   var projec
@@ -2633,32 +2633,32 @@
 ataset page. */%0A
-
 router.get('/com
@@ -2715,16 +2715,49 @@
 next) %7B%0A
+%09var db = pgp(connectionstring);%0A
   var da

update connection strings