package ru.yandex.wmconsole.servantlet;

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

import ru.yandex.common.framework.core.ServRequest;
import ru.yandex.common.framework.core.ServResponse;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.data.info.RecheckInfo;
import ru.yandex.wmconsole.service.HostInfoService;
import ru.yandex.wmconsole.service.VirusedHostService;
import ru.yandex.wmconsole.util.HostElementWrapper;
import ru.yandex.wmtools.common.data.wrappers.DateWrapper;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.error.UserProblem;
import ru.yandex.wmtools.common.servantlet.AbstractServantlet;

/**
 * User: azakharov
 * Date: 10.05.12
 * Time: 19:08
 */
public class VirusRecheckInfoServantlet extends AbstractServantlet {
    private static final String PARAM_HOST_NAME = "hostname";

    private VirusedHostService virusedHostService;
    private HostInfoService hostInfoService;

    @Override
    protected void doProcess(final ServRequest req, final ServResponse res) throws UserException, InternalException {

        final String hostName = StringUtils.trimToEmpty(getRequiredStringParam(req, PARAM_HOST_NAME));
        if (hostName.isEmpty()) {
            throw new UserException(UserProblem.ILLEGAL_PARAM_VALUE, "Hostname is empty", PARAM_HOST_NAME, hostName);
        }

        final BriefHostInfo briefHostInfo = hostInfoService.getBriefHostInfoByIdOrName(hostName);
        if (briefHostInfo == null) {
            throw new UserException(UserProblem.HOST_NOT_FOUND_IN_DATABASE, "Unable to find host", PARAM_HOST_NAME, hostName);
        }

        final RecheckInfo recheckInfo = virusedHostService.getRecheckInfo(briefHostInfo);
        if (recheckInfo != null && recheckInfo.getDate() != null) {
            res.addData(new HostElementWrapper(
                    new DateWrapper("recheck-request-date", recheckInfo.getDate()),
                    briefHostInfo));
        }
    }

    @Required
    public void setVirusedHostService(VirusedHostService virusedHostService) {
        this.virusedHostService = virusedHostService;
    }

    @Required
    public void setHostInfoService(HostInfoService hostInfoService) {
        this.hostInfoService = hostInfoService;
    }
}
