package ru.yandex.webmaster3.viewer.http.user.subscription;

import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

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.notifications.dao.TokensForUnsubscribeYDao;
import ru.yandex.webmaster3.storage.notifications.service.UserNotificationSettingsService;
import ru.yandex.webmaster3.storage.util.ydb.exception.WebmasterYdbException;
import ru.yandex.webmaster3.viewer.http.BaseWebmaster3Action;
import ru.yandex.webmaster3.viewer.http.request.AbstractFrontendRequest;

/**
 * Created by ifilippov5 on 12.03.18.
 */
@Description("Отписывает незалогиненного пользователя от обновлений")
@WriteAction
@Category("user")
@AllArgsConstructor(onConstructor_ = @Autowired)
public class UnsubscribeUserAction extends BaseWebmaster3Action<UnsubscribeUserAction.UnsubscribeRequest, UnsubscribeUserAction.UnsubscribeResponse> {
    private static final Logger log = LoggerFactory.getLogger(UnsubscribeUserAction.class);

    private TokensForUnsubscribeYDao tokensForUnsubscribeYDao;
    private UserNotificationSettingsService userNotificationSettingsService;

    @Override
    public UnsubscribeResponse process(UnsubscribeRequest request) {
        log.info("Want to unsubscribe user by token = {}", request.getToken());
        Long userId;
        try {
            userId = tokensForUnsubscribeYDao.getUserId(request.getToken());
            if (userId == null) {
                log.error("Unable find user by token = {}", request.getToken());
            } else {
                userNotificationSettingsService.saveEmail(userId, null); //Проставим галку "Не получать уведомления по почте"
            }
        } catch (WebmasterYdbException e) {
            throw new WebmasterException("Unable to unsubscribe user",
                    new WebmasterErrorResponse.YDBErrorResponse(this.getClass(), e), e);
        }

        return new UnsubscribeResponse();
    }

    public static class UnsubscribeRequest extends AbstractFrontendRequest {
        private String token;

        public String getToken() {
            return token;
        }

        @RequestQueryProperty(required = true)
        public void setToken(String token) {
            this.token = token;
        }
    }

    public static class UnsubscribeResponse implements ActionResponse.NormalResponse {
    }
}
