import * as express from 'express';
import * as path from "path";
import * as bodyParser from "body-parser";
import * as http from 'http';
import * as io from 'socket.io';
import { ConfigController } from './config.ctrl';
import { RhamtModelService } from 'raas-core';
import { Endpoint } from '../server/endpoint';

export class ConfigServer {

    public app: express.Application;
    private _server?: http.Server;
    private _configCtrl?: ConfigController;

    private endpoint: Endpoint;

    constructor(endpoint: Endpoint, private _modelService: RhamtModelService) {
        this.endpoint = endpoint;
    }

    public start(): void {
        this.app = express();
        this._server = this.app.listen(this.endpoint.port);
        let listener = io.listen(this._server);
        this._configCtrl = new ConfigController(this._modelService);
        listener.sockets.on('connection', socket => {
            console.log(`socket (${socket.id}) connected`);
            socket.on('log', (...args: any[]) => {
                this.log('from client: ', ...args);
            });
            socket.on('details', (data: any) => {
                console.log('server attempting to get details for: ' + data.id);
                let config = this._modelService.getConfiguration(data.id);
                if (config) {
                  console.log('got config!!!');
                }
                else {
                  console.log('couldnt find config');
                }
                
                // if (!data.id || !config) {
                //     console.log(`config (${data.id}) not found`);
                //     socket.emit('notFound', {config: {id: data.id}});
                //     socket.disconnect();
                // }
                // if (data.id !== this.config.id) {
                //     console.log(`server with config ${this.config.id} doesn't match requested ${data.id}`);
                //     socket.emit('missmatch', {message: `server with config ${this.config.id} doesn't match requested ${data.id}`});
                //     socket.disconnect();
                // }
                // else if (config) {
                    
                // }
            });
        });
        this.configServer();
        this.routes();
    }

    private configServer() {
        if (this.app) {
            this.app.set("views", path.join(__dirname, '..', '..', 'resources', 'views'));
            this.app.set("view engine", "jade");
            this.app.use(express.static(__dirname+'/../../resources'));
            this.app.use("/node_modules", express.static(__dirname+'/../../node_modules'));
            this.app.use("/out", express.static(__dirname+'/../../out'));        
            //mount logger
            //this.app.use(logger("dev"));
            this.app.use(bodyParser.json());
            this.app.use(bodyParser.urlencoded({ extended: true }));
            this.app.use(function(err: any, req: express.Request, res: express.Response, next: express.NextFunction) {
            err.status = 404;
            next(err);
            });
        }
      }

    private routes() {
        if (this.app && this._configCtrl) {
            let router = express.Router();
            router.get("/:id", this._configCtrl.get.bind(this._configCtrl));
            router.post("/:id", this._configCtrl.update.bind(this._configCtrl));
            this.app.use(router);
        }
    }

    public dispose(): void {
        if (this._server) {
            this._server.close();
        }
    }

    private log(message: string, ...args: any[]) {
        console.log(message, ...args);
    }
  }