package ru.yandex.webmaster3.storage.sitemap;

import java.util.List;
import java.util.UUID;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.data.WebmasterUser;
import ru.yandex.webmaster3.core.sitemap.UserSitemap;
import ru.yandex.webmaster3.core.sitemap.UserSitemapStatus;
import ru.yandex.webmaster3.storage.sitemap.dao.UserAddedSitemapYDao;

/**
 * @author aherman
 */
@Slf4j
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class UserSitemapService {

    private final UserAddedSitemapYDao userAddedSitemapYDao;

    public UserSitemap getUserSitemap(WebmasterHostId hostId, String sitemapUrl) {
        UUID sitemapId = SitemapUtils.createSitemapId(sitemapUrl);
        return getUserSitemap(hostId, sitemapId);
    }

    public UserSitemap getUserSitemap(WebmasterHostId hostId, UUID sitemapId) {
        return userAddedSitemapYDao.getSitemap(hostId, sitemapId);
    }

    public UserSitemap addUserSitemap(WebmasterHostId hostId, String sitemapUrl, WebmasterUser user) {
        UUID sitemapId = SitemapUtils.createSitemapId(sitemapUrl);
        UserSitemap userSitemap = new UserSitemap(hostId, sitemapUrl, sitemapId, DateTime.now(), false, null, UserSitemapStatus.NEW);
        userAddedSitemapYDao.addSitemap(userSitemap);
        return userSitemap;
    }

    public void deleteUserSitemap(WebmasterHostId hostId, UUID sitemapId) {
        UserSitemap sitemap = userAddedSitemapYDao.getSitemap(hostId, sitemapId);
        if (sitemap != null && !sitemap.isDeleted()) {
            userAddedSitemapYDao.markDeleted(hostId, sitemapId);
        } else if (sitemap == null) {
            log.warn("Trying to delete unknown sitemap with id {} for host {}", sitemapId, hostId);
        }
    }

    public List<UserSitemap> listUserSitemaps(WebmasterHostId hostId) {
        return userAddedSitemapYDao.listSitemaps(hostId);
    }
}
