var base = require("../lib/index.js");
import * as Express from "express";
import { PromiseOption } from ".";

// https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
let statuses:any = { 
    200: "OK",
    206: "Partial Content", 
    400: "Bad Request", 
    404: "Not Found", 
    429: "Too Many Requests", 
    500: "Internal Server Error", 
    503: "Service Unavailable" 
};

export default class StaticMethods {
    
    /**
    * Return a response to the caller
    * @param res 
    * @param status_code { 200: "OK", 206: "Partial Content", 400: "Bad Request", 404: "Not Found", 429: "Too Many Requests", 500: "Internal Server Error", 503: "Service Unavailable" }
    * @param message 
    * @param data 
    */
    public static sendResponse(res:Express.Response, status_code: number, message:any = undefined, data:any = {}, loggingLevel = base.LOG_LEVEL.INFO) {
        let status = statuses[status_code] || "Unknown";
        let response = JSON.stringify({ status: status, message: message, data: data });
        res.status(status_code);
        res.setHeader('Content-Type', 'application/json');
        res.send(response);
        base.logger().log(response, loggingLevel);
    }
    
    /**
    * wrap a method in promisefy
    * 
    * THIS has the expectation that he last params of the method is of type function(succes:boolean, data:any)
    */
    public static async promisefy(method:any, options:PromiseOption): Promise<any> {

        
        if(options.bind == undefined){
            options.bind = method;
        }

        if(options.controller == undefined ){

            options.controller = function(succes:boolean, data:any){
                if (succes) {
                    if(options.resolve != undefined)
                        options.resolve(data);
                }
                else {
                    if(options.reject != undefined)
                        options.reject(data);
                }
            }
        }

        try{
            let result = await new Promise(function(resolve, reject) {
                options.resolve = resolve;
                options.reject = reject;
                method.bind(options.bind)(...options.args, options.controller ); 
            });

            return {success: true, data:result};
        }catch(e){
            return {success: false, data:e};
        }
    }
}