import express from 'express';
import * as process from 'process';
import cors from 'cors';
import { IncomingMessage, ServerResponse  } from "http";
import { PGStudentTable } from './pgdbstudent.js';

class WebserviceProcess
{
	//private _hostname: string = process.env["SERVER_IP_ADDRESS"] || '127.0.0.1';	// In local computer
	private _port: number = 1339;
	
	constructor()
	{
	}
	
	// Just for debugging
	private DumpObject(obj: any, msg: string = ""): void
	{
		let output:string = msg;
		for (var property in obj) {
			output += property + ': ' + obj[property]+'; ';
		}
		console.log(output);		
	}
	
	Start(): void
	{
		let service = express();
		let dbname: string = "testdb1";
			
		service.get('/', function (req, res) {
			res.send('Welcome!');
		});
		
		service.get('/hi', function (req, res) {
			res.send('Hello!');
		});	
		
		service.get('/hello/:name', function (req, res) {
			res.send(`Hello ${req.params.name}`);
		});	
		
		service.get('/error', function (req, res) {
			res.status(403).end();
		});
		
		let corsOptions = {
		  origin: "*",
		  methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
		  allowedHeaders: "Authorization, Origin, Content-Type, Accept, X-Requested-With",
		  maxAge: 0//,      // Allow us to see preflight check, should be more like 1728000
		  // preflightContinue: false,
		  // optionsSuccessStatus: 204
		};
		
		service.use(cors(corsOptions));
				
		// Enable Express to read the Request Body
		service.use(express.json()) 						// for parsing application/json
		service.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
			
		service.post('/students', async (req, res) => {
			let studentDB: PGStudentTable = new PGStudentTable();
			await studentDB.Insert({
				Name: req.body.name,
				Age: req.body.age,
				Course: req.body.course
			}, res);
		});

		service.get('/students', async (req, res) => {
			let studentDB: PGStudentTable = new PGStudentTable();
			if(typeof req.query.name === "string")
			{
				await studentDB.SelectByName(req.query.name, res);
			}
			else
			{
				await studentDB.Select(res);
			}
		});
		
		service.get('/students/:id', async (req, res) => {
			let studentDB: PGStudentTable = new PGStudentTable();
			await studentDB.SelectById(parseInt(req.params.id), res);
		});
			
		service.patch('/students/:id', async (req, res) => {
			let studentDB: PGStudentTable = new PGStudentTable();
			await studentDB.Patch({
				Id: parseInt(req.params.id),
				Name: req.body.name,
				Age: req.body.age,
				Course: req.body.course
			}, res);
		});		
		
		service.delete('/students/:id', async (req, res) => {
			let studentDB: PGStudentTable = new PGStudentTable();
			await studentDB.Delete(parseInt(req.params.id), res);	
		});			
		
		service.listen(this._port, () => console.log(`Example web service listening at http://localhost:${this._port}`));		
	}		
}	
	
(function ()
{
	(new WebserviceProcess()).Start();
})();
	



