import { RequestOptions, HttpResponse } from '@talentsoft-opensource/integration-widget-contract'
import * as md5 from 'js-md5';

function formatDate(date: Date): string {
    const dd = date.getDate();
    const MM = date.getMonth()+1; //January is 0!
    const yyyy = date.getFullYear();
    const HH = date.getUTCHours();
    const mm = date.getMinutes();

    return `${yyyy}${MM}${dd}${HH}${mm}`;
}

function getDirectConnectHash(secretKey: string, login: string, date: Date) {
    const tokenBase = secretKey + formatDate(date) + login;
    return md5(tokenBase);
}


export class Proxy {
    constructor(
        public secretKey: string,
        public login: string)
        {}

    requestExternalResource(options: RequestOptions): Promise<HttpResponse> {
        const directConnectHash = getDirectConnectHash(this.secretKey, this.login, new Date());

        return fetch(
            options.url,
            {
                headers: {
                    'x-login': this.login,
                    'x-api-token': directConnectHash
                },
                method: options.verb,
                body: options.verb == 'GET' ? undefined : options.body,
            }
        ).then(async r => {
            const headers: { [k: string]: string } = {};
            r.headers.forEach((v: string, k: string) => { headers[k] = v; })
            const httpResponse: HttpResponse = {
                status: r.status,
                headers: headers,
                body: await r.text()
            }
            return httpResponse;
        });
    }
}
