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

import com.amazonaws.AmazonServiceException;
import com.amazonaws.http.HttpResponse;
import com.amazonaws.http.HttpResponseHandler;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class ResponseHandler implements HttpResponseHandler<String> {
    @Override
    public String handle(HttpResponse httpResponse) throws Exception {
        int status = httpResponse.getStatusCode();
        if(status < 200 || status >= 300) {
            AmazonServiceException ase = new AmazonServiceException("Unexpected status: " + status);
            ase.setStatusCode(status);
            throw ase;
        }
        InputStream stream = httpResponse.getContent();
        InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);
        StringBuilder sb = new StringBuilder();
        int byteRead;
        // read chunks from chat stream
        System.out.println("Reading from stream:");
        while ((byteRead = reader.read()) != -1) {
            System.out.print((char) byteRead);
            sb.append((char) byteRead);
        }
        return sb.toString();
    }

    @Override
    public boolean needsConnectionLeftOpen() {
        return false;
    }
}
