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

import java.util.UUID;

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.events2.client.HostEventLogClient;
import ru.yandex.webmaster3.core.events2.events.sitemap.DeleteUserSitemapEvent;
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(4)
@Category("sitemap")
public class DeleteUserSitemapAction extends AbstractUserVerifiedHostAction<DeleteUserSitemapRequest, DeleteUserSitemapResponse> {
    private static final Logger log = LoggerFactory.getLogger(DeleteUserSitemapAction.class);

    private UserSitemapService userSitemapService;
    private HostEventLogClient hostEventLogClient;

    @Override
    public DeleteUserSitemapResponse process(DeleteUserSitemapRequest request) {
        UUID sitemapId = request.getSitemapId();
        UserSitemap userSitemap = userSitemapService.getUserSitemap(request.getHostId(), sitemapId);
        if (userSitemap == null || userSitemap.isDeleted()) {
            log.warn("Sitemap already deleted: {}", sitemapId);
        } else {
            userSitemapService.deleteUserSitemap(request.getHostId(), sitemapId);
            hostEventLogClient.log(ViewerEventUtil.create(request,
                    new DeleteUserSitemapEvent(userSitemap.getSitemapUrl(), userSitemap.getSitemapId())
            ));
        }
        return new DeleteUserSitemapResponse.NormalResponse();
    }

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

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