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

import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import lombok.RequiredArgsConstructor;
import org.joda.time.Duration;
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.data.WebmasterUser;
import ru.yandex.webmaster3.core.http.Action;
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.core.util.RetryUtils;
import ru.yandex.webmaster3.storage.notifications.NotificationChannel;
import ru.yandex.webmaster3.storage.user.dao.UserNotificationChannelsYDao;
import ru.yandex.webmaster3.storage.user.dao.UserNotificationHostSettingsYDao;
import ru.yandex.webmaster3.storage.user.notification.HostNotificationMode;
import ru.yandex.webmaster3.storage.user.notification.NotificationType;
import ru.yandex.webmaster3.viewer.http.user.settings.TwoStateEnableEnum;

/**
 * @author avhaliullin
 */
@WriteAction
@Category("notifications")
@Description("Сбросить для хоста выбранные типы уведомлений в default")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class ResetHostNotification2SettingsAction extends Action<ResetHostNotification2SettingsRequest, ResetHostNotification2SettingsResponse> {

    private final UserNotificationHostSettingsYDao userNotificationHostSettingsYDao;
    private final UserNotificationChannelsYDao userNotificationChannelsYDao;

    @Override
    public ResetHostNotification2SettingsResponse process(ResetHostNotification2SettingsRequest request) throws WebmasterException {
        try {
            for (NotificationType notificationType : request.getTypes()) {
                RetryUtils.execute(RetryUtils.linearBackoff(3, Duration.standardSeconds(1)), () -> {
                    userNotificationHostSettingsYDao.updateMode(new WebmasterUser(request.getUserId()), request.getHostId(), notificationType, NotificationChannel.EMAIL, HostNotificationMode.DEFAULT);
                    userNotificationHostSettingsYDao.updateMode(new WebmasterUser(request.getUserId()), request.getHostId(), notificationType, NotificationChannel.SERVICE, HostNotificationMode.DEFAULT);
                });
            }
            Map<NotificationType, Set<NotificationChannel>> userChannels = userNotificationChannelsYDao.getUserSettings(request.getUserId());
            Map<NotificationType, Map<NotificationChannel, TwoStateEnableEnum>> result = new HashMap<>();
            for (Map.Entry<NotificationType, Set<NotificationChannel>> entry : userChannels.entrySet()) {
                Set<NotificationChannel> channels = entry.getValue();
                Map<NotificationChannel, TwoStateEnableEnum> notificationTypeSettings = new EnumMap<>(NotificationChannel.class);
                for (NotificationChannel channel : entry.getKey().getSupportedChannels()) {
                    notificationTypeSettings.put(channel, TwoStateEnableEnum.fromBoolean(channels.contains(channel)));
                }
                result.put(entry.getKey(), notificationTypeSettings);
            }
            return new ResetHostNotification2SettingsResponse(result);
        } catch (InterruptedException e) {
            throw new WebmasterException("Failed to reset host notification settings",
                    new WebmasterErrorResponse.YDBErrorResponse(getClass(), e), e);
        }
    }
}
