package ru.yandex.wmconsole.data.info.spider;

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

import org.springframework.beans.factory.annotation.Required;

import ru.yandex.wmtools.common.util.SqlUtil;

/**
 * @author avhaliullin
 */
public class CommonCodesGroupFactory extends SpiderCodesGroupFactory {
    private Set<Byte> groupNumbers;
    private List<Integer> knownCodes;
    private String groupNameFormatString = "%dxx";
    private String otherSubgroupNameFormatString = "other_%s";

    @Override
    protected List<SpiderCodesSubgroupInfo> getSubgroups(Set<String> requestedSubgroups) {
        List<SpiderCodesSubgroupInfo> subgroups = new ArrayList<SpiderCodesSubgroupInfo>();
        if (knownCodes != null) {
            for (Integer code : knownCodes) {
                if (requestedSubgroups.contains(code.toString())) {
                    subgroups.add(new SpiderCodesSubgroupInfo(code.toString(), " hs.code = " + code.toString() + " "));
                }
            }
        }
        if (requestedSubgroups.contains(getOtherSubgroupName())) {
            StringBuilder filter = new StringBuilder();
            filter.append(" ( ");
            int i = 0;
            for (Byte groupNum : groupNumbers) {
                if (i > 0) {
                    filter.append(" OR ");
                }
                filter.append(" hs.code BETWEEN ")
                        .append(groupNum)
                        .append("00 AND ")
                        .append(groupNum)
                        .append("99 ");
                i++;
            }
            filter.append(" ) ");
            if (knownCodes != null && !knownCodes.isEmpty()) {
                filter.append(" AND NOT hs.code IN (")
                        .append(SqlUtil.getCommaSeparatedList(knownCodes))
                        .append(") ");
            }
            subgroups.add(new SpiderCodesSubgroupInfo(getOtherSubgroupName(), filter.toString()));
        }
        return subgroups;
    }

    @Override
    protected String getGroupName() {
        return String.format(groupNameFormatString, groupNumbers.toArray());
    }

    public void setGroupNameFormatString(String groupNameFormatString) {
        this.groupNameFormatString = groupNameFormatString;
    }

    public void setOtherSubgroupNameFormatString(String otherSubgroupNameFormatString) {
        this.otherSubgroupNameFormatString = otherSubgroupNameFormatString;
    }

    public void setKnownCodes(List<Integer> knownCodes) {
        this.knownCodes = knownCodes;
    }

    @Required
    public void setGroupNumbers(Set<Byte> groupNumbers) {
        this.groupNumbers = groupNumbers;
    }

    private String getOtherSubgroupName() {
        return String.format(otherSubgroupNameFormatString, getGroupName());
    }
}
