package ru.yandex.webmaster3.worker.http.statistic;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.webmaster3.core.statistic.HostGraphUtils;
import ru.yandex.webmaster3.core.worker.task.WorkerTaskType;
import ru.yandex.webmaster3.worker.queue.TaskHostStatistics;

/**
 * @author aherman
 */
public class TaskHostsImageServlet extends HttpServlet {
    private TaskHostStatistics taskHostStatistics;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType("image/png");
        String taskType = req.getParameter("taskType");
        if (StringUtils.isEmpty(taskType)) {
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        WorkerTaskType workerTaskType = WorkerTaskType.R.valueOfOrUnknown(taskType);
        if (workerTaskType == WorkerTaskType.UNKNOWN) {
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        TaskHostStatistics.Stats currentStatistic = taskHostStatistics.getCurrentStatistic(workerTaskType);
        if (currentStatistic.getBitSet() == null) {
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        try (ServletOutputStream outputStream = resp.getOutputStream();) {
            HostGraphUtils.writeToImage(currentStatistic.getBits(), currentStatistic.getBitSet(), outputStream);
        }
    }

    @Required
    public void setTaskHostStatistics(TaskHostStatistics taskHostStatistics) {
        this.taskHostStatistics = taskHostStatistics;
    }
}
