package ru.yandex.webmaster3.coordinator.http.searchbase;

import java.util.NavigableMap;

import org.joda.time.Instant;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.Action;
import ru.yandex.webmaster3.core.http.ActionRequest;
import ru.yandex.webmaster3.core.http.ActionResponse;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.searchbase.SearchBaseUpdateInfo;
import ru.yandex.webmaster3.storage.util.ydb.exception.WebmasterYdbException;
import ru.yandex.webmaster3.storage.searchbase.dao.SearchBaseUpdatesYDao;

/**
 * @author lester
 */
public class GetSearchBaseInfoAction extends Action<GetSearchBaseInfoAction.Request, GetSearchBaseInfoAction.Response> {
    private SearchBaseUpdatesYDao searchBaseUpdatesYDao;

    @Override
    public Response process(Request request) throws WebmasterException {
        try {
            NavigableMap<Instant, SearchBaseUpdateInfo> updatesHistory = searchBaseUpdatesYDao.getUpdatesHistory();

            if (updatesHistory.isEmpty()) {
                String message = "We do not have records about search bases";
                throw new WebmasterException(message, new WebmasterErrorResponse.InternalUnknownErrorResponse(getClass(), message));
            }

            Instant lastBaseSwitchTime = updatesHistory.lastKey();
            return new Response(updatesHistory.get(lastBaseSwitchTime));
        } catch (WebmasterYdbException e) {
            throw new WebmasterException("Unable get searchbase status",
                    new WebmasterErrorResponse.YDBErrorResponse(getClass(), e), e);
        }
    }

    public static class Request implements ActionRequest {}

    public static class Response implements ActionResponse.NormalResponse {
        private final SearchBaseUpdateInfo searchBaseUpdateInfo;

        public Response(SearchBaseUpdateInfo searchBaseUpdateInfo) {
            this.searchBaseUpdateInfo = searchBaseUpdateInfo;
        }

        public SearchBaseUpdateInfo getSearchBaseUpdateInfo() {
            return searchBaseUpdateInfo;
        }
    }

    @Required
    public void setSearchBaseUpdatesYDao(SearchBaseUpdatesYDao searchBaseUpdatesYDao) {
        this.searchBaseUpdatesYDao = searchBaseUpdatesYDao;
    }
}
