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

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.ActionResponse;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.http.RequestQueryProperty;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.user.settings.FrontendUserSettingsKey;
import ru.yandex.webmaster3.storage.user.settings.FrontendUserSettingsYDao;
import ru.yandex.webmaster3.storage.util.ydb.exception.WebmasterYdbException;
import ru.yandex.webmaster3.viewer.http.AbstractUserAction;
import ru.yandex.webmaster3.viewer.http.AbstractUserRequest;
import ru.yandex.webmaster3.viewer.http.user.settings.frontend.GetUserSettingsAction.Request;
import ru.yandex.webmaster3.viewer.http.user.settings.frontend.GetUserSettingsAction.Response;

/**
 * @author Oleg Bazdyrev
 * @see WMC-4465
 */
@ReadAction
@Category("user")
@Description("Посмотреть настройки пользователя")
@Component("/user/settings/read")
public class GetUserSettingsAction extends AbstractUserAction<Request, Response> {
    private final FrontendUserSettingsYDao frontendUserSettingsYDao;

    @Autowired
    public GetUserSettingsAction(FrontendUserSettingsYDao frontendUserSettingsYDao) {
        this.frontendUserSettingsYDao = frontendUserSettingsYDao;
    }

    @Override
    public Response process(Request request) {
        try {
            String value = frontendUserSettingsYDao.getValue(
                    request.getUserId(),
                    request.getKey()
            );
            return new Response(value);
        } catch (WebmasterYdbException e) {
            throw new WebmasterException("Failed to get user settings",
                    new WebmasterErrorResponse.YDBErrorResponse(getClass(), e), e);
        }
    }


    public static class Request extends AbstractUserRequest {

        private FrontendUserSettingsKey key;

        public FrontendUserSettingsKey getKey() {
            return key;
        }

        @RequestQueryProperty(required = true)
        @Description("Название ключа настроек")
        public void setKey(FrontendUserSettingsKey key) {
            this.key = key;
        }
    }

    public static class Response implements ActionResponse.NormalResponse {

        private final String value;

        public Response(String value) {
            this.value = value;
        }

        @Description("Запрошенное значение")
        public String getValue() {
            return value;
        }
    }
}
