import { HttpService } from "@nestjs/axios";
import { Response } from 'express';
import { 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";

@Controller('serviceprovider')
export class ServiceProviderController {

    defaultQueryDatas: DefaultQueryData;

    constructor(private http: HttpService) {


    }
    // @Post()
    // postServiceProvider() {

    // }

    @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;
        }


    }

}