package ru.kayashov.bar.service.integration.translate;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import ru.kayashov.bar.model.api.translate.Request;
import ru.kayashov.bar.model.api.translate.Response;
import ru.kayashov.bar.model.api.translate.Translate;
import ru.kayashov.bar.service.RestUtil;

import java.util.List;
import java.util.Optional;

@Slf4j
@UtilityClass
public class TranslateService {

    private static final String TOKEN = "t1.9euelZrJyoyTmZGQyc2TiZCWlYyLiu3rnpWazsubi8vOzcycms6Znc2dkI7l8_dgXlNC-e9UAyJ4_t3z9yANUUL571QDInj-zef1656Vms2Uio2JmJ6OxpucmoqNjZ6J7_zF656Vms2Uio2JmJ6OxpucmoqNjZ6J.uXSVsrpZcSgQ9qz0-wx6WR79rvq14QCtlC6tnWvah33YRrNqSEBFXBwqMoEq18nG3wHElKE4NsHXK3lxV9SSBQ";

    public static String translate(String text) {
        return sendTranslate(text)
                .map(TranslateService::getTranslateText)
                .orElseThrow(RuntimeException::new);
    }

    public static String softTranslate(String text) {
        Optional<ResponseEntity<Response>> opt = sendTranslate(text);
        if(opt.isPresent()) {
            return TranslateService.getTranslateText(opt.get());
        } else {
            log.warn("Не удалось перевести текст {}", text);
            return text;
        }
    }

    private static Optional<ResponseEntity<Response>> sendTranslate(String text) {
        return RestUtil.sendRequest(Response.class,
                RequestEntity.post("https://translate.api.cloud.yandex.net/translate/v2/translate")
                        .header("Authorization", "Bearer " + TOKEN)
                        .body(new Request(List.of(text))));
    }

    private static String getTranslateText(ResponseEntity<Response> response) {
        Response resp = response.getBody();
        StringBuilder sb = new StringBuilder();
        List<Translate> translates = resp.getTranslations();
        for(Translate translate : translates) {
            sb.append(translate.getText());
        }
        return sb.toString();
    }
}
