package ru.yandex.qe.dispenser.ws;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;

import com.google.common.net.MediaType;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import io.swagger.annotations.Authorization;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;

import ru.yandex.qe.dispenser.swagger.DispenserSecurityDefinition;
import ru.yandex.qe.dispenser.swagger.SwaggerTags;

@Api(tags = {SwaggerTags.DISPENSER_API}, authorizations = {@Authorization(value = DispenserSecurityDefinition.AUTHORIZATION_SCHEME_NAME)})
public abstract class HtmlPage extends ServiceBase {
    @Autowired
    private Configuration templatesConfig;

    @GET
    @NotNull
    @Path("")
    public Response get(@QueryParam("whoami") @Nullable final String whoami) throws IOException {
        final Template template = templatesConfig.getTemplate(getPathInBundle(), StandardCharsets.UTF_8.name());
        final ByteArrayOutputStream pageBytes = new ByteArrayOutputStream();
        try {
            final Object dataModel = getDataModel(whoami);
            if (dataModel == null) {
                return Response.noContent().entity("No data model").build();
            }
            template.process(dataModel, new OutputStreamWriter(pageBytes, StandardCharsets.UTF_8));
        } catch (TemplateException e) {
            return Response.serverError().entity(e.getMessage()).build();
        }
        return Response.ok(pageBytes.toByteArray())
                .type(MediaType.HTML_UTF_8.toString())
                .entity(pageBytes.toByteArray())
                .build();
    }

    @NotNull
    public abstract String getPathInBundle();

    @Nullable
    public Object getDataModel(@Nullable final String login) throws TemplateException {
        return new Object();
    }
}
