package ru.yandex.webmaster3.api.host.filter;

import org.springframework.beans.factory.annotation.Required;
import ru.yandex.webmaster3.api.host.filter.trait.ApiUserVerifiedHostRequest;
import ru.yandex.webmaster3.api.http.rest.request.ApiRequest;
import ru.yandex.webmaster3.api.http.rest.request.ApiRequestFilter;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.data.WebmasterUser;
import ru.yandex.webmaster3.core.user.UserVerifiedHost;
import ru.yandex.webmaster3.storage.user.service.UserHostsService;

/**
 * @author avhaliullin
 */
public class ApiUserVerifiedHostFilter<Req extends ApiRequest<?> & ApiUserVerifiedHostRequest> implements ApiRequestFilter<Req, ApiUserVerifiedHostError> {
    private UserHostsService userHostsService;

    @Override
    public ApiUserVerifiedHostError applyFilter(Req req) {
        WebmasterHostId hostId = req.getHostId();
        UserVerifiedHost userVerifiedHost = userHostsService.getVerifiedHost(new WebmasterUser(req.getUserId()), hostId);
        if (userVerifiedHost != null) {
            req.setUserVerifiedHost(userVerifiedHost);
            return null;
        }
        return new ApiUserVerifiedHostError.HostNotVerifiedError(hostId);
    }

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