package ru.yandex.webmaster3.worker.notifications;

import lombok.RequiredArgsConstructor;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.springframework.beans.factory.annotation.Autowired;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.notification.LanguageEnum;
import ru.yandex.webmaster3.core.util.IdUtils;
import ru.yandex.webmaster3.storage.postpone.PostWelcomeEmailData;
import ru.yandex.webmaster3.worker.notifications.services.PostWelcomeMessageBodyBuilderService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class PostwelcomeTestHandler extends AbstractHandler {

    private final PostWelcomeMessageBodyBuilderService postWelcomeMessageBodyBuilderService;

    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        if (target.equals("/postwelcome/template")) {
            baseRequest.setHandled(true);
            String lang = baseRequest.getParameter("lang");

            openPostWelcomeTemplate(
                    lang == null ? LanguageEnum.DEFAULT_EMAIL_LANGUAGE : LanguageEnum.fromString(lang),
                    response
            );
        }
    }

    private void openPostWelcomeTemplate(LanguageEnum lang, HttpServletResponse response) throws IOException {
        long userId = 1468912441;
        WebmasterHostId hostId = IdUtils.urlToHostId("https://сайт123.рф");
        boolean isShortEmail = false;
        boolean isTurboEcommerse = false;

        PostWelcomeEmailData postWelcomeEmailData = new PostWelcomeEmailData(userId, hostId, lang);
        String body = postWelcomeMessageBodyBuilderService.buildBody(postWelcomeEmailData, isShortEmail, isTurboEcommerse);

        //из EmailSenderService
        String content = body.replaceAll("webmaster.yandex.ru", "webmaster.test.yandex.ru");

        response.setStatus(HttpServletResponse.SC_OK);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        writer.print(content);
        writer.flush();
    }
}
