package ru.yandex.webmaster3.viewer.http.filter;

import org.springframework.beans.factory.annotation.Required;
import ru.yandex.autodoc.common.doc.params.ParamDescriptor;
import ru.yandex.webmaster3.core.http.RequestFilter;
import ru.yandex.webmaster3.core.http.filter.HostIsVerifiedByUserFilterResponse;
import ru.yandex.webmaster3.core.http.request.RequestContext;
import ru.yandex.webmaster3.core.http.request.WebmasterHostIdConverter;
import ru.yandex.webmaster3.core.user.UserVerifiedHost;
import ru.yandex.webmaster3.storage.user.service.UserHostsService;
import ru.yandex.webmaster3.core.http.request.VerifiedHostIdAware;

/**
 * @author aherman
 */
public class HostIsVerifiedByUserFilter implements RequestFilter<VerifiedHostIdAware, HostIsVerifiedByUserFilterResponse> {
    private UserHostsService userHostsService;

    @Override
    public HostIsVerifiedByUserFilterResponse beforeRequest(RequestContext ctx, VerifiedHostIdAware req) {
        UserVerifiedHost verifiedHost = userHostsService.getVerifiedHost(req.getWebmasterUser(), req.getHostId());
        if (verifiedHost == null) {
            if (userHostsService.getUnverifiedHost(req.getWebmasterUser(), req.getHostId()) == null) {
                return new HostIsVerifiedByUserFilterResponse.HostNotAdded(getClass(), req.getHostId());
            } else {
                return new HostIsVerifiedByUserFilterResponse.HostNotVerified(this.getClass(), req.getHostId());
            }
        }
        req.setUserVerifiedHost(verifiedHost);
        return null;
    }

    @Override
    public ParamDescriptor clarifyParameter(ParamDescriptor param) {
        if (param.getName().equals("hostId")) {
            return new ParamDescriptor(param.getName(), true, WebmasterHostIdConverter.PARAM_TYPE, null,
                    "подтвержденный пользователем хост", param.getExtraInfos());
        } else {
            return param;
        }
    }

    @Required
    public void setUserHostsService(UserHostsService userHostsService) {
        this.userHostsService = userHostsService;
    }
}
