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

import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.storage.util.ydb.exception.WebmasterYdbException;
import ru.yandex.webmaster3.storage.notifications.NotificationChannel;
import ru.yandex.webmaster3.storage.notifications.service.UserNotificationSettingsService;
import ru.yandex.webmaster3.storage.user.notification.HostNotificationMode;
import ru.yandex.webmaster3.storage.user.notification.NotificationType;
import ru.yandex.webmaster3.storage.user.notification.Setting;
import ru.yandex.webmaster3.viewer.http.AbstractUserAction;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author aherman
 */
@WriteAction
@AllArgsConstructor(onConstructor_ = @Autowired)
public class UpdateHostNotification2DefaultSettingAction extends
        AbstractUserAction<UpdateHostNotification2DefaultSettingRequest, UpdateHostNotification2DefaultSettingResponse> {
    private final UserNotificationSettingsService userNotificationSettingsService;

    @Override
    public UpdateHostNotification2DefaultSettingResponse process(UpdateHostNotification2DefaultSettingRequest request) {
        List<List<Setting>> updatedSettingsList = new ArrayList<>();

        for (NotificationType type : request.getTypes()) {
            Set<NotificationChannel> settings;
            try {
                settings = userNotificationSettingsService.updateDefaultSettings(request.getWebmasterUser(),
                        type, request.getChannel(), request.getMode());
            } catch (WebmasterYdbException e) {
                throw new WebmasterException("Unable to update settings",
                        new WebmasterErrorResponse.YDBErrorResponse(getClass(), e), e);
            }

            List<Setting> updatedSettings = new ArrayList<>();
            for (NotificationChannel channel : NotificationChannel.values()) {
                HostNotificationMode mode = HostNotificationMode.DISABLED;
                if (settings.contains(channel)) {
                    mode = HostNotificationMode.ENABLED;
                }
                updatedSettings.add(new Setting(
                        type, channel, mode
                ));
            }
            updatedSettingsList.add(updatedSettings);
        }
        if (request.getChannel() == NotificationChannel.EMAIL && request.getMode() == HostNotificationMode.ENABLED) {
            if (userNotificationSettingsService.getUserEmail(request.getUserId()) == null) {
                return new UpdateHostNotification2DefaultSettingResponse.NoEmailWarning();
            }
        }
        return new UpdateHostNotification2DefaultSettingResponse.NormalResponse(updatedSettingsList);
    }
}
