import com.gridnine.xtrip.common.model.booking.commission.FeePropertiesIndex
import com.gridnine.xtrip.common.model.booking.commission.FeeType
import com.gridnine.xtrip.common.model.entity.EntityStorage
import com.gridnine.xtrip.common.model.profile.ModelContract
import com.gridnine.xtrip.common.model.profile.ModelContractIndex
import com.gridnine.xtrip.common.model.rules.standard.RuleResultValue
import com.gridnine.xtrip.common.search.SearchCriterion
import com.gridnine.xtrip.common.search.SearchQuery

import java.util.concurrent.atomic.AtomicInteger

SearchQuery query = new SearchQuery()

query.getCriteria().getCriterions().add(
        SearchCriterion.eq(
                FeePropertiesIndex.Property.type.name(), FeeType.MANUALLY_CALCULATED))

List<FeePropertiesIndex> feeIndices =
        EntityStorage.get().search(FeePropertiesIndex.class, query).getData()

if (feeIndices.isEmpty()) {
    answer.booleanData = false
    answer.textData = "No FeeProperties of MANUALLY_CALCULATED type found."
    return
}

//message("Fees: " + feeIndices.size())

query = new SearchQuery()
query.getCriteria().getCriterions().add(
        SearchCriterion.ne(ModelContractIndex.Property.rulesCount.name(), 0))
List<ModelContractIndex> indices =
        EntityStorage.get().search(ModelContractIndex.class, query).getData()

if (indices.isEmpty()) {
    answer.booleanData = false
    answer.textData = "No ModelContract with rules found."
    return
}

//message("Model contracts: " + indices.size())

StringBuilder builder = new StringBuilder()

indices.each { mci ->
    AtomicInteger yes = new AtomicInteger(0)
    ModelContract mc = EntityStorage.get().resolve(mci.getSource())?.getEntity()
    mc.getRuleSet().getRules().each {rs ->
        if (rs.getResults().any { rr ->
                (rr.getValue() instanceof RuleResultValue) && (feeIndices.any { fpi ->
                    fpi.getSource().getUid().equals(((RuleResultValue) rr.getValue()).getTarget().getUid())
                })
            }) {
            yes.incrementAndGet()
            builder.append("Rule set: ").append(mci.getName()).append(" - Rule: ").append(rs.getName()).append("\n")
        }
    }
    if (yes.get() > 0) {
        answer.booleanData = true
        builder.append("Rule set: ").append(mci.getName()).append("\n")
//        message(mci.getName() + " - " + yes.get())
    }
}
if (builder.size() == 0) {
//    message("No ModelContract with rules with manual fees involved found.")
    answer.textData = "No ModelContract with rules with manual fees involved found."
    answer.booleanData = false
} else {
    answer.textData = builder.toString()
//    message(builder.toString())
}
