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

import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Component;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.api.http.auth.Permission;
import ru.yandex.webmaster3.api.http.rest.AbstractApiAction;
import ru.yandex.webmaster3.api.http.util.ApiEventUtil;
import ru.yandex.webmaster3.api.sitemap.data.ApiSitemapId;
import ru.yandex.webmaster3.core.data.WebmasterUser;
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.sitemap.UserSitemap;
import ru.yandex.webmaster3.storage.sitemap.UserSitemapService;

/**
 * @author avhaliullin
 */
@Description("Добавить сайтмеп")
@Category("sitemap")
@Component
public class AddSitemapAction extends AbstractApiAction<AddSitemapRequest, AddSitemapResponse> {
    private HostEventLogClient hostEventLogClient;
    private UserSitemapService userSitemapService;

    public AddSitemapAction() {
        super(Permission.COMMON);
    }

    @Override
    public AddSitemapResponse process(AddSitemapRequest request) {
        String sitemapUrl = request.getEntity().getUrl().toExternalForm();
        UserSitemap userSitemap = userSitemapService.getUserSitemap(request.getHostId(), sitemapUrl);
        if (userSitemap == null || userSitemap.isDeleted()) {
            userSitemap = userSitemapService.addUserSitemap(request.getHostId(), sitemapUrl, new WebmasterUser(request.getUserId()));
            hostEventLogClient.log(ApiEventUtil.create(request,
                    new AddUserSitemapEvent(userSitemap.getSitemapUrl(), userSitemap.getSitemapId())
            ));
        } else {
            return new AddSitemapResponse.SitemapAlreadyAddedResponse(
                    request.getUserId(), userSitemap.getHostId(),
                    new ApiSitemapId(null, userSitemap.getSitemapId())
            );
        }
        return new AddSitemapResponse.NormalResponse(
                request.getUserId(), request.getHostId(),
                new ApiSitemapId(null, userSitemap.getSitemapId())
        );
    }

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

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