package ru.yandex.webmaster3.viewer.http.regions;

import org.springframework.beans.factory.annotation.Required;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.data.L10nEnum;
import ru.yandex.webmaster3.core.data.W3RegionInfo;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.http.RequestTimeout;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.regions.W3RegionsTreeService;
import ru.yandex.webmaster3.viewer.http.BaseWebmaster3Action;
import ru.yandex.webmaster3.viewer.http.regions2.RegionView;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import static ru.yandex.webmaster3.core.regions.RegionUtils.CHILDREN_VISIBILITY_PREDICATE;
import static ru.yandex.webmaster3.core.regions.RegionUtils.PARENT_VISIBILITY_PREDICATE;

/**
 * @author avhaliullin
 */
@ReadAction
@Description("Информация о регионе")
@RequestTimeout(1)
@Category("regions")
public class RegionInfoAction extends BaseWebmaster3Action<RegionInfoRequest, RegionInfoResponse> {
    private W3RegionsTreeService w3regionsTreeService;

    @Override
    public RegionInfoResponse process(RegionInfoRequest request) throws WebmasterException {
        int regionId = request.getRegionId();
        W3RegionInfo regionInfo = w3regionsTreeService.getExactRegionInfo(regionId);
        if (regionInfo == null) {
            return new RegionInfoResponse.UnknownRegionResponse(getClass(), regionId);
        }

        List<W3RegionInfo> parents = w3regionsTreeService.getVisibleParentsChain(regionId, PARENT_VISIBILITY_PREDICATE);
        Set<W3RegionInfo> children = w3regionsTreeService.getVisibleChildren(regionId, CHILDREN_VISIBILITY_PREDICATE);
        List<RegionView> proposed = new ArrayList<>();
        //TODO: Temporarily hack to display proposed regions
        if (regionId == 0) {
            proposed.add(new RegionView(225));
            proposed.add(new RegionView(187));
            proposed.add(new RegionView(149));
            proposed.add(new RegionView(159));
            if (request.getLocale() == L10nEnum.TR) {
                proposed.add(new RegionView(983));
            }
        }
        return new RegionInfoResponse.NormalResponse(REGION_MAPPER.apply(regionInfo),
                parents.stream().map(REGION_MAPPER).collect(Collectors.toList()),
                children.stream().sorted(W3RegionInfo.BY_ID).map(REGION_MAPPER).collect(Collectors.toList()),
                proposed);
    }

    @Required
    public void setW3regionsTreeService(W3RegionsTreeService w3regionsTreeService) {
        this.w3regionsTreeService = w3regionsTreeService;
    }

    private static final Function<W3RegionInfo, RegionView> REGION_MAPPER = region -> {
        return region == null ? null : new RegionView(region.getId());
    };
}
