package ru.yandex.webmaster3.viewer.http.user.settings.frontend;

import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
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.WebmasterException;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.util.ydb.exception.WebmasterYdbException;
import ru.yandex.webmaster3.storage.user.settings.FrontendUserHostSettingsYDao;
import ru.yandex.webmaster3.viewer.http.AbstractUserAddedHostAction;

import java.util.Collections;

/**
 * @author shabashoff
 */
@ReadAction
@Category("user")
@Component("/user/host/settings/multipleRead")
@AllArgsConstructor(onConstructor_ = {@Autowired})
@Description("Посмотреть настройки пользователя для хостов")
public class GetMultipleUserHostSettingsAction extends AbstractUserAddedHostAction<GetMultipleUserHostSettingsRequest, GetMultipleUserHostSettingsResponse> {
    private final FrontendUserHostSettingsYDao frontendUserHostSettingsYDao;

    @Override
    public GetMultipleUserHostSettingsResponse process(GetMultipleUserHostSettingsRequest request) {
        if (CollectionUtils.isEmpty(request.getKeys())) {
            return new GetMultipleUserHostSettingsResponse(Collections.emptyMap());
        }

        try {
            var settings = frontendUserHostSettingsYDao.getValues(
                    request.getUserId(),
                    request.getHostId(),
                    request.getKeys()
            );

            request.getKeys().forEach(key -> settings.putIfAbsent(key, null)); // чтобы явно показать поле с null'ом
            return new GetMultipleUserHostSettingsResponse(settings);
        } catch (WebmasterYdbException e) {
            throw new WebmasterException("Failed to get multiple user host settings",
                    new WebmasterErrorResponse.YDBErrorResponse(getClass(), e), e);
        }
    }
}
