package ru.yandex.webmaster3.viewer.http.searchquery.recommended;

import lombok.RequiredArgsConstructor;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.ActionResponse;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.util.ydb.exception.WebmasterYdbException;
import ru.yandex.webmaster3.storage.recommendedquery.dao.HostsWaitFirstRecommendedYDao;
import ru.yandex.webmaster3.storage.recommendedquery.dao.HostsWithOpenedRecommendedYDao;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostRequest;

/**
 * Created by ifilippov5 on 07.11.17.
 */
@Description("Открыть рекомендованные запросы для хоста")
@WriteAction
@Category("recommended")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class OpenRecommendedForHostAction extends AbstractUserVerifiedHostAction<OpenRecommendedForHostAction.Req, OpenRecommendedForHostAction.Res> {
    private final HostsWithOpenedRecommendedYDao hostsWithOpenedRecommendedYDao;
    private final HostsWaitFirstRecommendedYDao hostsWaitFirstRecommendedYDao;

    @Override
    public Res process(Req request) {
        try {
            hostsWithOpenedRecommendedYDao.insertHost(request.getHostId(), DateTime.now(), request.getUserId());
            hostsWaitFirstRecommendedYDao.insertHost(request.getHostId());
        } catch (WebmasterYdbException e) {
            throw new WebmasterException("Failed to insert",
                    new WebmasterErrorResponse.YDBErrorResponse(getClass(), e), e);
        }
        return new Res.NormalResponse();
    }

    public static class Req extends AbstractUserVerifiedHostRequest {}

    public static abstract class Res implements ActionResponse {
        public static class NormalResponse extends Res implements ActionResponse.NormalResponse {
        }
    }
}
