package org.jeecg.modules.okki.translate.service;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.DefaultRequest;
import com.amazonaws.Request;
import com.amazonaws.Response;
import com.amazonaws.auth.AWS4Signer;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.http.AmazonHttpClient;
import com.amazonaws.http.ExecutionContext;
import com.amazonaws.http.HttpMethodName;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.okki.translate.param.AwsParaphraseParam;
import org.jeecg.modules.okki.translate.param.AwsTranslateOptionParam;
import org.jeecg.modules.okki.translate.param.AwsTranslateParam;
import org.jeecg.modules.okki.translate.tools.ErrorHandler;
import org.jeecg.modules.okki.translate.tools.ResponseHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AwsParaphraseService {

    @Value("${aws.region}")
    private String Region;

    @Value("${aws.host}")
    private String Host;

    @Value("${aws.service}")
    private String Service;

    public String doParaphrase(AwsParaphraseParam awsParaphraseParam) {
        Gson gson = new Gson();
        String str = gson.toJson(awsParaphraseParam);
        InputStream is = new ByteArrayInputStream(str.getBytes());
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("content-type", "application/json");
        Request<Void> request = new DefaultRequest<>(Service); //Request to Lambda
        request.setHttpMethod(HttpMethodName.POST);
        request.setContent(is);
        request.setHeaders(headerMap);
        request.setEndpoint(URI.create(Host + "/api/v1/generation/paraphrase"));
        //Sign it...
        AWS4Signer signer = new AWS4Signer();
        signer.setRegionName(Region);
        signer.setServiceName(request.getServiceName());
        // automatically get the credentials from Env for EC2/Lambda roles
        signer.sign(request, new DefaultAWSCredentialsProviderChain().getCredentials());
        //Execute it and get the response...
        Response<String> rsp = new AmazonHttpClient(new ClientConfiguration())
                .requestExecutionBuilder()
                .executionContext(new ExecutionContext(true))
                .request(request)
                .errorResponseHandler(new ErrorHandler())
                .execute(new ResponseHandler());
        return rsp.getAwsResponse();
    }
}
