package ru.yandex.webmaster3.worker.dashboard;

import java.util.List;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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.RequestQueryProperty;
import ru.yandex.webmaster3.storage.clickhouse.ClickhouseTableInfo;
import ru.yandex.webmaster3.storage.clickhouse.TableState;
import ru.yandex.webmaster3.storage.clickhouse.dao.LegacyClickhouseTablesYDao;

@Component("/tableInfo/updateState")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Slf4j
public class UpdateTableStateAction extends Action<UpdateTableStateAction.Request, UpdateTableStateAction.Response> {
    private final LegacyClickhouseTablesYDao legacyClickhouseTablesYDao;

    @Override
    public Response process(Request request) throws WebmasterException {
        final ClickhouseTableInfo newTableInfo = request.getNewTableInfo();
        final List<ClickhouseTableInfo> tableInfos = legacyClickhouseTablesYDao.listTables(newTableInfo.getType());
        final TableState newState = newTableInfo.getState();
        final ClickhouseTableInfo oldTableInfo = tableInfos.stream()
                .filter(tableInfo -> tableInfo.getTableId().equals(newTableInfo.getTableId()))
                .findFirst().orElseThrow(IllegalStateException::new);
        if (oldTableInfo.getState().equals(newState)) {
            return new Response();
        }
        if (oldTableInfo.getState().isOnline()) {
            final long countOnlineTables = tableInfos.stream()
                    .filter(tableInfo -> tableInfo.getState().isOnline())
                    .count();
            if (countOnlineTables == 1) {
                throw new IllegalStateException("Expected more than 1 online table");
            }
        }
        legacyClickhouseTablesYDao.update(oldTableInfo.withState(newState));

        return new Response();
    }

    @Setter(onMethod_ = @RequestQueryProperty)
    @Getter
    public static class Request implements ActionRequest {
        ClickhouseTableInfo newTableInfo;
    }

    public static class Response implements ActionResponse.NormalResponse {
    }
}
