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

import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.notifications.service.UserNotificationSettingsService;
import ru.yandex.webmaster3.storage.user.notification.HostSetting;
import ru.yandex.webmaster3.storage.user.notification.NotificationType;
import ru.yandex.webmaster3.storage.user.notification.Setting;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author aherman
 */
@WriteAction
@Category("notifications")
@AllArgsConstructor(onConstructor_ = @Autowired)
public class UpdateHostNotification2SettingAction extends
        AbstractUserVerifiedHostAction<UpdateHostNotification2SettingRequest, UpdateHostNotification2SettingResponse> {
    private UserNotificationSettingsService userNotificationSettingsService;

    @Override
    public UpdateHostNotification2SettingResponse process(UpdateHostNotification2SettingRequest request) {
        List<HostSetting> settings = new ArrayList<>();
        boolean noEmail = false;
        for (NotificationType type : request.getTypes()) {
            if (!UserNotificationSettingsService.PER_HOST_NOTIFICATION_TYPES.contains(type)) {
                settings.add(new HostSetting(request.getHostId(), false, Collections.emptyList()));
                continue;
            }

            userNotificationSettingsService.updateHostSettings(request.getUserId(), request.getHostId(), type, request.getChannel(), request.getMode());
            if (userNotificationSettingsService.shouldAlertNoEmail(request.getUserId(), type, request.getChannel(), request.getMode())) {
                noEmail = true;
            }
            settings.add(new HostSetting(request.getHostId(),
                    false, Collections.singletonList(
                    new Setting(
                            type,
                            request.getChannel(),
                            request.getMode())
            )
            ));
        }

        if (noEmail) {
            return new UpdateHostNotification2SettingResponse.NoEmailWarning();
        }
        return new UpdateHostNotification2SettingResponse.NormalResponse(
                settings
        );
    }
}
