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

import lombok.extern.slf4j.Slf4j;
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.RequestQueryProperty;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.http.WriteAction;
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.UpdateUserSettingsAction.Request;
import ru.yandex.webmaster3.viewer.http.user.settings.frontend.UpdateUserSettingsAction.Response;

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


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

    @Override
    public Response process(Request request) {
        try {
            frontendUserSettingsYDao.updateValue(
                    request.getUserId(),
                    request.getKey(),
                    request.getValue()
            );

            return new Response();
        } catch (WebmasterYdbException e) {
            throw new WebmasterException("Failed to update user settings",
                    new WebmasterErrorResponse.YDBErrorResponse(getClass(), e), e);
        }
    }

    public static class Request extends AbstractUserRequest {

        private FrontendUserSettingsKey key;
        private String value;

        public FrontendUserSettingsKey getKey() {
            return key;
        }

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

        public String getValue() {
            return value;
        }

        @RequestQueryProperty
        @Description("Значение настройки")
        public void setValue(String value) {
            this.value = value;
        }
    }

    public static class Response implements ActionResponse.NormalResponse {

    }
}
