import {IServiceProxy} from "./IServiceProxy";
import {IService} from "mslib";

class ServiceProxy implements IServiceProxy {

    private service: IService
    private sid: string
    private contentType: string

    constructor(sid: string, contentType: string, service: IService) {
        this.sid = sid;
        this.service = service;
        this.contentType = contentType
    }

    async doService(request): Promise<any> {
        let allParams = {}
        if (this.needRawBody(request)) {
            allParams = {rawBody: request.body}
        } else {
            allParams = request.body || {};
        }
        this.copyProperty(request.params, allParams)
        this.copyProperty(request.query, allParams)

        return this.service.doService(allParams)
    }

    private needRawBody(request) {
        return this.isString(request.body)
            && (this.isNotEmpty(request.params)
                || this.isNotEmpty(request.query))
    }

    private isString(target: any) {
        return typeof target === 'string'
    }

    private isNotEmpty(target: any) {
        return target && Object.keys(target).length > 0
    }

    private copyProperty(source, target) {
        if (!source) {
            return
        }
        for (const fileName in source) {
            target[fileName] = source[fileName]
        }
    }

    getContentType() {
        return this.contentType
    }


}

export {ServiceProxy}