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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.events2.client.HostEventLogClient;
import ru.yandex.webmaster3.core.events2.events.sitemap.AddUserSitemapEvent;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.http.RequestTimeout;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.core.sitemap.UserSitemap;
import ru.yandex.webmaster3.storage.sitemap.UserSitemapService;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.util.ViewerEventUtil;

/**
 * @author aherman
 */
@WriteAction
@Description(value = "Добавление пользовательских сайтмапов")
@RequestTimeout(15)
@Category("sitemap")
public class AddUserSitemapAction extends AbstractUserVerifiedHostAction<AddUserSitemapRequest, AddUserSitemapResponse> {
    private static final Logger log = LoggerFactory.getLogger(AddUserSitemapAction.class);

    private UserSitemapService userSitemapService;
    private HostEventLogClient hostEventLogClient;

    @Override
    public AddUserSitemapResponse process(AddUserSitemapRequest request) throws WebmasterException {
        String sitemapUrl = request.getSitemapUrl().toExternalForm();
        UserSitemap userSitemap = userSitemapService.getUserSitemap(request.getHostId(), sitemapUrl);
        if (userSitemap != null && !userSitemap.isDeleted()) {
            log.warn("Sitemap already added: {}", userSitemap.getSitemapId());
        } else {
            userSitemap = userSitemapService.addUserSitemap(request.getHostId(), sitemapUrl, request.getWebmasterUser());
            hostEventLogClient.log(ViewerEventUtil.create(request,
                    new AddUserSitemapEvent(userSitemap.getSitemapUrl(), userSitemap.getSitemapId())
            ));
        }

        return new AddUserSitemapResponse.NormalResponse(userSitemap);
    }

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

    @Required
    public void setHostEventLogClient(HostEventLogClient hostEventLogClient) {
        this.hostEventLogClient = hostEventLogClient;
    }
}
