var express = require('express');
var router = express.Router();

var options = require('./dbconfig');

//
// Postgresql
//
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);

router.get('/:davcna/:id?', function (req, res, next) {
  req.setTimeout(0);
  if(!req.params.id) req.params.id = 0;
  var odgovor = {
    title: 'Naš denar',
    stran: req.params.id, 
    next: parseInt(req.params.id) + 1, 
    prev: parseInt(req.params.id) - 1, 
    davcna: req.params.davcna,
    sifrapu: -1,
    narociladelez_organ: -1,
    rtr: {},
  };
  var stevec = 0;
  var vseZahteve = 15;

  pool.query('SELECT sum(vsota_prejemkov) STOLPIC, leto, mesec FROM dupu WHERE davcna_stevilka = $1 GROUP BY leto, mesec', [req.params.davcna], function (err, transResult) {
    if(err) {
      throw err;
    }
    var date = new Date();
    var mesec = date.getMonth() + 1;
    var leto = date.getFullYear();
    var vsehMesecev = (leto - 2003) * 12 + mesec;
    var stolpci = [];
    for (var i = 0; i < vsehMesecev; i++) {
      stolpci.push(0);
    }
    for (var j = 0; j < transResult.rows.length; j++) {
      stolpci[(transResult.rows[j].leto - 2003) * 12 + transResult.rows[j].mesec-1] = transResult.rows[j].stolpic;
    }
    odgovor.transakcije = stolpci;
    stevec++;
    console.log("1");
    if(stevec == vseZahteve) {
      res.render('podj', odgovor);        
    }
  });

  pool.query('SELECT kreditojemalec_naziv, kreditojemalec_sedez, davcna, posta, postna_st, kreditodajalec, st_pogodbe, znesek_eur, vrsta_posla, (extract(day FROM datum_pogodbe) || \'.\' ||  extract(month from datum_pogodbe) || \'.\' || extract(year from datum_pogodbe)) DATUM, zavarovanje_vrsta, zavarovanje_predmet FROM dutb WHERE davcna = $1 ORDER BY datum_pogodbe', [req.params.davcna], function (err, dutbResult) {
    if(err) {
      throw err;
    }
    odgovor.dutb = dutbResult.rows;
    stevec++;
    console.log("2");
    if(stevec == vseZahteve) {
      res.render('podj', odgovor);
    }
  });
  
  pool.query('select distinct (extract(day FROM datum) || \'.\' || extract(month from datum) || \'.\' || extract(year from datum)) DATUM_TECAJNICE, uradni_tecaj tocke, datum from tecajnica where znak = ( select znak from delnice where davcna = $1 LIMIT 1 ) order by tecajnica.datum asc;', [req.params.davcna], function (err, tecajnica) {
	  if(err) {
		  throw err
	  }
	  odgovor.tecajnica = tecajnica.rows
	  stevec++
	  console.log("3")
	  if(stevec == vseZahteve) {
		  res.render('podj', odgovor)
	  }
  })

  pool.query('SELECT * FROM lokacija WHERE davcna_stevilka = $1 LIMIT 1', [req.params.davcna], function (err, lokacijaZS) {
    if(err) {
      throw err;
    }
    odgovor.lokacijaZS = lokacijaZS.rows;
    stevec++;
    console.log("4");
    if(stevec == vseZahteve) {
      res.render('podj', odgovor);
    }
  });

  pool.query('SELECT kreditodajalec, sum(znesek_eur) ZNESEK FROM dutb WHERE davcna = $1 GROUP BY KREDITODAJALEC', [req.params.davcna], function (err, dutbDelezi) {
    if(err) {
      throw err;
    }
    odgovor.dutbdelez = dutbDelezi.rows;
    stevec++;
    console.log("5");
    if(stevec == vseZahteve) {
      res.render('podj', odgovor);        
    }
  })

  pool.query('SELECT zavezanec, naziv, naslov, razred, (extract(day FROM dolg_na_dan) || \'.\' || extract(month FROM dolg_na_dan) || \'.\' || extract(year FROM dolg_na_dan)) datum_veljavnosti FROM furs WHERE zavezanec = $1 ORDER BY dolg_na_dan DESC', [req.params.davcna], function (err, neplacniki) {
    if(err) {
      throw err;
    }
    odgovor.neplacniki = neplacniki.rows;
    stevec++;
    console.log("6");
    if(stevec == vseZahteve) {
      res.render('podj', odgovor);        
    }
  });

  pool.query('SELECT * FROM evidence WHERE davcna = $1 ORDER BY leto DESC', [req.params.davcna], function (err, evidence) {
	if(err) {
      throw err;
	}
	odgovor.evidence = evidence.rows;
	stevec++;
	console.log("7")
	if(stevec == vseZahteve) {
      res.render('podj', odgovor)
	}
  })
  
  pool.query('SELECT organ, SUM(globa) globa FROM evidence WHERE davcna = $1 GROUP BY organ', [req.params.davcna], function (err, evidence_graf) {
	if(err) {
      throw err;
	}
	odgovor.grafEvidence = evidence_graf.rows;
	stevec++;
	console.log("8")
	if(stevec == vseZahteve) {
      res.render('podj', odgovor)
	}
  });
  
  pool.query('SELECT * FROM prs WHERE substring(ma, 1,7) = (select substring(ma, 1,7) FROM prs WHERE davcna = $1 LIMIT 1)', [req.params.davcna], function (err, podruznice) {
    if(err) {
      throw err;
    }
    odgovor.podruznice = podruznice.rows;
    stevec++;
    console.log("9");
    if(stevec == vseZahteve) {
      res.render('podj', odgovor);        
    }
  })
 
  pool.query('SELECT id, (extract(day FROM uppd.datum) || \'.\' ||  extract(month FROM uppd.datum) || \'.\' ||  extract(year FROM uppd.datum)) DATUM_TRANSAKCIJE, stranka, sedez_stranke, matst_stranke, prejemnik, sedez_prejemnika, znesek, val, namen_nakazila FROM uppd WHERE substring(matst_stranke, 1, 7) = (select substring(ma, 1, 7) FROM prs WHERE prs.davcna = $1 LIMIT 1) ORDER BY datum DESC', [req.params.davcna], function (err, uppd) {
    if(err) {
      throw err;
    }
    odgovor.uppd = uppd.rows;
    stevec++;
    console.log("10");
    if(stevec == vseZahteve) {
      res.render('podj', odgovor);
    }
  });

  pool.query('SELECT organ, maticna, davcna, sifra_pu, naslov, posta, tip_omejitve, ps_naziv, drzava, ps_maticna, ps_davcna, mid, ps_naslov, ps_posta, (extract(day FROM datum_od) || \'.\' ||  extract(month from datum_od) || \'.\' || extract(year from datum_od)) DATUM_OD, (extract(day FROM datum_do) || \'.\' ||  extract(month from datum_do) || \'.\' || extract(year from datum_do)) DATUM_DO FROM omejitve WHERE ps_davcna = $1', [req.params.davcna], function (err, omejitve) {
    if(err) {
      throw err;
    }
    odgovor.omejitve = omejitve.rows;
    stevec++;
    console.log("11");
    if(stevec == vseZahteve) {
      res.render('podj', odgovor);        
    }
  })

  pool.query('SELECT * FROM prs WHERE davcna = $1 LIMIT 1', [req.params.davcna], function (err, subjekt_ZS) {
    if(err) {
      throw err;
    }
    odgovor.subjektZS = subjekt_ZS.rows;
    stevec++;
    console.log("12");
    if(stevec == vseZahteve) {
      res.render('podj', odgovor);        
    }
  })
  
  pool.query('SELECT *, (extract(day FROM datum_objave) || \'.\' || extract(month FROM datum_objave) || \'.\' || extract(year FROM datum_objave)) datum FROM narocila WHERE davcna_ponudnika = $1 ORDER BY datum_objave DESC', [req.params.davcna], function (err, narocila) {
    if(err) {
      throw err
    }
    odgovor.narocila = narocila.rows
    stevec++
    console.log("13")
    if(stevec == vseZahteve) {
      res.render('podj', odgovor)
    }
  })
  
  pool.query('SELECT sum(vrednost_brez_ddv) znesek, narocnik FROM narocila WHERE davcna_ponudnika = $1 GROUP BY narocnik ORDER BY znesek DESC LIMIT 5', [req.params.davcna], function (err, narocila) {
    if(err) {
      throw err
    }
    odgovor.narociladelez_podj = narocila.rows
    stevec++
    console.log("14")
    if(stevec == vseZahteve) {
      res.render('podj', odgovor)
    }
  })

  pool.query('SELECT sum(vrednost_brez_ddv) znesek FROM narocila WHERE davcna_ponudnika = $1', [req.params.davcna], function(err, vsotanarocil){
    if(err) {
      throw err
    }
    odgovor.vsotanarocil=vsotanarocil.rows[0].znesek
    stevec++
    console.log("15")
    if(stevec == vseZahteve) {
      res.render('podj', odgovor)
    }
  }) 
});

module.exports = router;
