package ru.yandex.webmaster3.viewer.http.turbo.landing;

import java.util.List;
import java.util.Optional;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.http.Action;
import ru.yandex.webmaster3.core.http.ActionRequest;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.turbo.model.landing.TurboLandingPreview;
import ru.yandex.webmaster3.storage.util.ydb.exception.WebmasterYdbException;
import ru.yandex.webmaster3.storage.host.CommonDataState;
import ru.yandex.webmaster3.storage.settings.SettingsService;
import ru.yandex.webmaster3.storage.turbo.dao.landing.TurboLandingPreviewsYDao;
import ru.yandex.webmaster3.viewer.http.turbo.landing.GetTurboLandingInfoAction.Request;

import static ru.yandex.webmaster3.storage.host.CommonDataType.TURBO_ACTIVE_HOSTS_COUNT;

/**
 * Created by Oleg Bazdyrev on 12/11/2018.
 */
@ReadAction
@Category("turbo")
@Component("/turbo/landing/info")
@Description("Получение данных для дашборда")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class GetTurboLandingInfoAction extends Action<Request, GetTurboLandingInfoResponse> {

    private final SettingsService settingsService;
    private final TurboLandingPreviewsYDao turboLandingPreviewsYDao;

    @Override
    public GetTurboLandingInfoResponse process(Request request) {
        try {
            long activeHostsCount = Optional.ofNullable(settingsService.getSettingOrNull(TURBO_ACTIVE_HOSTS_COUNT))
                    .map(CommonDataState::getValue).map(Long::parseLong).orElse(0L);
            List<TurboLandingPreview> previews = turboLandingPreviewsYDao.listAll();
            return new GetTurboLandingInfoResponse(activeHostsCount, previews);
        } catch (WebmasterYdbException e) {
            throw e.asUnchecked("Cassandra error", getClass());
        }
    }

    public static final class Request implements ActionRequest {

    }

}
