package ru.yandex.webmaster3.storage.util;

import java.util.function.Function;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.sitestructure.NewSiteStructure;
import ru.yandex.webmaster3.core.sitestructure.SiteTreeNode;
import ru.yandex.webmaster3.core.sitestructure.StructureNodeFilter;
import ru.yandex.webmaster3.storage.sitestructure.SiteStructureService;
import ru.yandex.webmaster3.storage.user.dao.UserSiteTreeYDao;
import ru.yandex.webmaster3.storage.util.clickhouse2.condition.Condition;
import ru.yandex.webmaster3.storage.util.clickhouse2.condition.TextLikeCondition;

/**
 * @author avhaliullin
 */
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class StructureFilterService {

    private final SiteStructureService siteStructureService;
    private final UserSiteTreeYDao userSiteTreeYDao;

    public Condition getNodeCondition(Long nodeId, WebmasterHostId hostId,
                                      Function<TextLikeCondition.Builder, TextLikeCondition> pathConditionBuilder) {
        if (nodeId == null || nodeId == NewSiteStructure.ROOT_NODE_ID) {
            return Condition.trueCondition();
        } else {
            StructureNodeFilter nodeFilter = getNodeFilter(hostId, nodeId);
            if (nodeFilter == null) {
                //Такой ноды нет, так что "отфильтровали всё"
                return Condition.falseCondition();
            }
            TextLikeCondition.Builder condBuilder = TextLikeCondition.newBuilder();
            for (StructureNodeFilter.Part part : nodeFilter.getFilterParts()) {
                if (part instanceof StructureNodeFilter.StringPart) {
                    condBuilder.append(((StructureNodeFilter.StringPart) part).getValue());
                } else {
                    condBuilder.appendWildcard();
                }
            }
            return pathConditionBuilder.apply(condBuilder);
        }
    }

    public StructureNodeFilter getNodeFilter(WebmasterHostId hostId, long nodeId) {
        StructureNodeFilter filter =
                StructureNodeFilter.makeFilterForAutoNode(siteStructureService.getSiteTreeNodes(hostId).getLeft(),
                        nodeId);
        if (filter == null) {
            SiteTreeNode node = userSiteTreeYDao.getUserTreeNode(hostId, nodeId);
            filter = StructureNodeFilter.makeFilterForUserNode(node);
        }
        return filter;
    }

}
