/* eslint-disable prefer-const */
/* eslint-disable prettier/prettier */
import { HttpService } from "@nestjs/axios";
import { Response } from 'express';
import { Body, Controller, Get, Post, Query, Req, Res } from "@nestjs/common";
import { DefaultQueryData, ServiceProviderData } from "src/CommonMicroserviceModule/message/FISAppMessageJSUtility/dependencies/dependencies";
import { QueryClientController } from "src/QueryClientProxy/queryClient.controller";
import { AxiosRequestConfig } from "axios";

@Controller('serviceprovider')
export class ServiceProviderController {

    defaultQueryDatas: DefaultQueryData;

    constructor(private http: HttpService) {


    }
    @Post()
    postServiceProvider(@Res() res: Response, @Body() params: { id: string, name: string, path: string, req: any }) {
        let checkServiceProvider: ServiceProviderData;
        if (!params.id && !params.name) {
            return "No service provider url found";

        }

        checkServiceProvider = QueryClientController.provider1.getActiveProviders().find((provider: ServiceProviderData) => { //get the actual provider lists
            if (provider.id == params.id) {
                return provider;
            }

            if (provider.name == params.name) {
                return provider;
            }
        })
        // console.log("PROVIDER ::: " + JSON.stringify(checkServiceProvider));
        let data: any;

        try {
            data = JSON.parse(params.req); //JSON
        }
        catch (err) {
            data = params.req // string
        }



        if (!checkServiceProvider) {
            return "No service provider found";
        } else if (checkServiceProvider.url > "") { // is valid url 

            res.setHeader("Content-Type", "application/json");

            const http_config: AxiosRequestConfig = {
                responseType: "stream"
            };

            http_config.method = "post";
            http_config.url = checkServiceProvider.url + params.path;
            http_config.data = data;

            //let sub = this.http.post(checkServiceProvider.url + query.path,data).subscribe({
            this.http.axiosRef.request(http_config).then((axiosRes) => {
                axiosRes.data.on('data', buffer => {
                    res.write(buffer.toString()); // New message
                })

                axiosRes.data.on('error', err => {
                    res.write(JSON.stringify(err.message, null, 4)); // This need to fisapp error message
                    res.end(); // Close/complete the message.
                })

                axiosRes.data.on('end', () => {
                    res.end()
                })

            })
        }

    }

    @Get()
    getServiceProvider(@Res() res: Response, @Query() query: { id: string, name: string, path: string }) {

        let checkServiceProvider: ServiceProviderData;

        if (!query.id && !query.name) {
            return "No service provider url found";

        }

        checkServiceProvider = QueryClientController.provider1.getActiveProviders().find((provider: ServiceProviderData) => { //get the actual provider lists
            if (provider.id == query.id) {
                return provider;
            }

            if (provider.name == query.name) {
                return provider;
            }
        })


        if (!checkServiceProvider) {
            return "No service provider found";
        } else if (checkServiceProvider.url > "") { // is valid url 

            let sub = this.http.get(checkServiceProvider.url + query.path).subscribe(
                x => {
                    let newResponse = {};
                    newResponse['headers'] = x['headers'];
                    newResponse['data'] = x['data'];

                    res.header = newResponse['headers'];
                    res.write(newResponse['data']);
                    return res.status(200).send();
                },
                err => {
                    console.log(err); return err;
                },
                () => {
                    console.log("Complete.");
                    sub.unsubscribe();
                }
            )
            return sub;
        }


    }

}