import com.gridnine.xtrip.common.model.EntityContainer
import com.gridnine.xtrip.common.model.dict.CommunicationType
import com.gridnine.xtrip.common.model.entity.EntityStorage
import com.gridnine.xtrip.common.model.profile.Communication
import com.gridnine.xtrip.common.model.profile.Organization
import com.gridnine.xtrip.common.model.profile.OrganizationIndex
import com.gridnine.xtrip.common.model.profile.OrganizationType
import com.gridnine.xtrip.common.search.SearchCriterion
import com.gridnine.xtrip.common.search.SearchQuery
import com.gridnine.xtrip.common.util.TextUtil

SearchQuery query = new SearchQuery()

query.getCriteria().getCriterions().add(SearchCriterion.contains(OrganizationIndex.Property.types.name(), OrganizationType.CORPORATE_CLIENT))

List<OrganizationIndex> indexes = EntityStorage.get().search(OrganizationIndex.class, query).getData()

for(OrganizationIndex index : indexes) {

    EntityContainer<Organization> organizationContainer = EntityStorage.get().resolve(index.getSource())

    if(organizationContainer != null) {

        Organization organization = organizationContainer.getEntity()

        Iterator<Communication> iterator = organization.getCommunications().iterator()

        boolean changed = false

        while(iterator.hasNext()) {

            Communication communication = iterator.next()

            if ((communication.getType() == CommunicationType.WORK_PHONE)
            || (communication.getType() == CommunicationType.HOME_PHONE)
            || (communication.getType() == CommunicationType.FAX)
            || (communication.getType() == CommunicationType.MOBILE)
            || (communication.getType() == CommunicationType.AGENCY)
            || (communication.getType() == CommunicationType.HOTEL)
            || (communication.getType() == CommunicationType.CELL)
            || (communication.getType() == CommunicationType.EMERGENCY)) {

                iterator.remove()
                changed = true
            }
        }

        if(changed) {

            organizationContainer.getVersionInfo().setDataSource("organization-phones-remove-task")

            EntityStorage.get().save(organizationContainer, true)
        }
    }
}