//
// Postresql
//

var Pool = require('pg').Pool;
var config = {
  user: 'matjaz',
  password: 'mesnjak',
  database: 'supervizor',
  host: 'server.dev',
  port: 5432,
  max: 10,
  idleTimeoutMillis: 30000,
};
var pool = new Pool(config);


module.exports = {
  jePrijavljen: function jePrijavljen(sessionid, callback) {
    if(sessionid) {
      pool.query('SELECT * FROM seja WHERE sid = $1', [sessionid], function(err, result) {
        if(err) {
          callback("Napaka1", false)
        }
        else {
          if(!result.rows[0]) {
            callback("Napaka2", false)
          }
          else {
            var userid = result.rows[0].userid;
            var potece = result.rows[0].potece;
            var datePotece = new Date(Date.parse(potece + "+0000"));
            if(datePotece < Date.now()) {
              callback("Napaka3", false)
            }
            else {
              pool.query('SELECT * FROM uporabniki WHERE id = $1', [userid], function(err, uporabnik) {
                if(err) {
                  callback("Napaka3.1", false)
                }
                else {
                  callback(null, uporabnik.rows[0])
                }
              })
            }
          }
        }
      })
    }
    else {
      callback("Napaka4", false)
    }
  },
  jeAdmin: function jeAdmin(sessionid, callback) {
    if(sessionid) {
      pool.query('SELECT * FROM seja WHERE sid = $1', [sessionid], function(err, result) {
        if(err) {
          callback('Napaka 1', false)
        }
        else {
          if(!result.rows[0]) {
            callback('Napaka 2', false)
          }
          else {
            var userid = result.rows[0].userid;
            var potece = result.rows[0].potece;
            var datePotece = new Date(Date.parse(potece + "+0000"));
            if(datePotece < Date.now()) {
              callback('Napaka 3', false)
            }
            else {
              pool.query('SELECT * FROM uporabniki WHERE id = $1', [userid], function(err, uporabnik) {
                if(err) {
                  callback('Napaka 4', false)
                }
                else if(uporabnik.rows[0].vloga = 'admin') {
                  callback(null, uporabnik.rows[0])
                }
                else {
                  callback('Napaka 5', false)
                }
              })
            }
          }
        }
      })
    }
    else {
      callback('Napaka 6', false)
    }
  }
}