package ru.yandex.webmaster3.viewer.http.turbo.commerce;

import java.util.List;
import java.util.stream.Collectors;

import lombok.RequiredArgsConstructor;
import lombok.Value;
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.data.WebmasterHostId;
import ru.yandex.webmaster3.core.http.ActionResponse;
import ru.yandex.webmaster3.core.http.RequestQueryProperty;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.turbo.model.TurboHostSettings;
import ru.yandex.webmaster3.core.turbo.model.commerce.TurboCommerceSettings;
import ru.yandex.webmaster3.core.turbo.model.desktop.TurboDesktopSettings;
import ru.yandex.webmaster3.core.turbo.model.feed.TurboFeedInfo;
import ru.yandex.webmaster3.core.turbo.model.feed.TurboFeedSettings;
import ru.yandex.webmaster3.core.turbo.model.feed.TurboFeedState;
import ru.yandex.webmaster3.core.turbo.model.feed.TurboFeedType;
import ru.yandex.webmaster3.core.util.WwwUtil;
import ru.yandex.webmaster3.storage.events.service.WMCEventsService;
import ru.yandex.webmaster3.storage.turbo.service.TurboFeedsService;
import ru.yandex.webmaster3.storage.turbo.service.settings.TurboSettingsService;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostRequest;
import ru.yandex.webmaster3.viewer.http.turbo.commerce.ActivateTurboCommerceFeedsAction.Request;
import ru.yandex.webmaster3.viewer.http.turbo.commerce.ActivateTurboCommerceFeedsAction.Response;

/**
 * Created by Oleg Bazdyrev on 01/09/2020.
 */
@Slf4j
@WriteAction
@Component("/turbo/ecommerce/activate")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Category("turbo")
public class ActivateTurboCommerceFeedsAction extends AbstractUserVerifiedHostAction<Request, Response> {

    private final TurboFeedsService turboFeedsService;
    private final TurboSettingsService turboSettingsService;
    private final WMCEventsService wmcEventsService;

    @Override
    public Response process(Request request) {
        WebmasterHostId hostId = request.getHostId();
        String domain = WwwUtil.cutWWWAndM(hostId);
        // поищем фиды для активации
        List<TurboFeedSettings> feeds = turboFeedsService.getFeeds(domain).stream()
                .filter(feed -> feed.getState() != TurboFeedState.DELETED)
                .filter(feed -> feed.getType() == TurboFeedType.YML)
                .collect(Collectors.toList());
        if (feeds.isEmpty()) {
            return new Response.NoYmlFeedsResponse();
        }
        // проверим настройки е-коммерс
        TurboHostSettings turboHostSettings = turboSettingsService.getSettings(domain);
        TurboCommerceSettings tcs = turboHostSettings.getCommerceSettings();
        boolean orderMethodSelected = tcs != null && tcs.isOrderMethodSelected();
        if (request.activate && !orderMethodSelected) {
            return new Response.InvalidCommerceSettingsResponse();
        }
        // WMC-7106 - отключаем десктоп при включении YML
        TurboDesktopSettings tds = turboSettingsService.getDesktopSettings(domain);
        if (request.activate && Boolean.TRUE.equals(tds.getEnabled())) {
            turboSettingsService.updateDesktopSettings(domain,
                    new TurboDesktopSettings.TurboDesktopSettingsBuilder(tds).setEnabled(false).build());
        }

        // активируем все YML-фиды
        feeds = feeds.stream().map(feed -> feed.activate(request.activate)).collect(Collectors.toList());
        // сохраняем
        feeds.forEach(turboFeedsService::insertFeed);
        turboSettingsService.notifyAboutSettingsChange(domain, turboHostSettings, null, null);

        List<TurboFeedInfo> feedInfos = turboFeedsService.getFeedsWithStatistics(domain).entrySet().stream()
                .filter(entry -> entry.getKey().getState() != TurboFeedState.DELETED)
                .filter(entry -> entry.getKey().getType() == TurboFeedType.YML)
                .map(entry -> new TurboFeedInfo(entry.getKey(), entry.getValue(), null))
                .collect(Collectors.toList());
        return new Response.NormalResponse(feedInfos);
    }

    public static final class Request extends AbstractUserVerifiedHostRequest {
        private boolean activate = true;

        @RequestQueryProperty
        public void setActivate(boolean activate) {
            this.activate = activate;
        }
    }

    public abstract static class Response implements ActionResponse {

        public enum ErrorCode {
            ACTIVATE_TURBO_COMMERCE_FEEDS__NO_YML_FEEDS,
            ACTIVATE_TURBO_COMMERCE_FEEDS__INVALID_COMMERCE_SETTINGS,
        }

        @Value
        public static final class NormalResponse extends Response implements ActionResponse.NormalResponse {
            private final List<TurboFeedInfo> feeds;
        }

        @Description("Нет YML-фидов")
        public static final class NoYmlFeedsResponse extends Response implements ActionResponse.ErrorResponse {

            @Override
            public Enum<?> getCode() {
                return ErrorCode.ACTIVATE_TURBO_COMMERCE_FEEDS__NO_YML_FEEDS;
            }
        }

        @Description("Нет всех требуемых настроек магазинов")
        public static final class InvalidCommerceSettingsResponse extends Response implements ActionResponse.ErrorResponse {

            @Override
            public Enum<?> getCode() {
                return ErrorCode.ACTIVATE_TURBO_COMMERCE_FEEDS__INVALID_COMMERCE_SETTINGS;
            }
        }

    }
}
