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

import org.springframework.beans.factory.annotation.Required;
import ru.yandex.webmaster3.api.http.rest.request.ApiRequest;
import ru.yandex.webmaster3.api.http.rest.request.ApiRequestFilter;
import ru.yandex.webmaster3.api.sitemap.filter.trait.UserAddedSitemapRequest;
import ru.yandex.webmaster3.core.sitemap.UserSitemap;
import ru.yandex.webmaster3.storage.sitemap.UserSitemapService;

/**
 * @author avhaliullin
 */
public class UserAddedSitemapFilter<Req extends ApiRequest<?> & UserAddedSitemapRequest> implements ApiRequestFilter<Req, UserAddedSitemapError> {
    private UserSitemapService userSitemapService;

    @Override
    public UserAddedSitemapError applyFilter(Req req) {
        if (req.getSitemapId().getParentId() != null) {
            return new UserAddedSitemapError.SitemapNotAddedError(req.getHostId(), req.getSitemapId());
        }
        UserSitemap userSitemap = userSitemapService.getUserSitemap(req.getHostId(), req.getSitemapId().getId());
        if (userSitemap == null) {
            return new UserAddedSitemapError.SitemapNotAddedError(req.getHostId(), req.getSitemapId());
        }
        req.setUserSitemap(userSitemap);
        return null;
    }

    @Required
    public void setUserSitemapService(UserSitemapService userSitemapService) {
        this.userSitemapService = userSitemapService;
    }
}
