import java.util.stream.Collectors

import org.slf4j.Logger
import org.slf4j.LoggerFactory

import com.gridnine.xtrip.common.model.EntityContainer;
import com.gridnine.xtrip.common.model.EntityReference
import com.gridnine.xtrip.common.model.booking.BaseProduct
import com.gridnine.xtrip.common.model.booking.BookingFile
import com.gridnine.xtrip.common.model.booking.CommonProductIndex
import com.gridnine.xtrip.common.model.entity.EntityStorage;
import com.gridnine.xtrip.common.model.finance.FinanceDocument
import com.gridnine.xtrip.common.model.finance.FinanceDocumentRecordIndex
import com.gridnine.xtrip.common.model.finance.VatViewMode
import com.gridnine.xtrip.common.model.handlers.ProductHandler
import com.gridnine.xtrip.common.model.profile.Organization;
import com.gridnine.xtrip.common.search.SearchCriterion
import com.gridnine.xtrip.common.search.SearchQuery

// Script create for TUI to update
// finance documents vat view mode

Logger logger = LoggerFactory.getLogger('groovy-script')

logger.info("Update finance documents vat view mode: started")

VatViewMode mode = VatViewMode.ALWAYS
boolean except = true
String clientUid = ""

logger.info("Update finance documents vat view mode: mode is " + mode)

EntityReference<Organization> customer = new EntityReference<>(clientUid, Organization.class, null)

SearchQuery query = new SearchQuery()

query.getCriteria().getCriterions().add(except ? SearchCriterion.ne(FinanceDocumentRecordIndex.Property.customer.name(), customer) : SearchCriterion.eq(FinanceDocumentRecordIndex.Property.customer.name(), customer))

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

logger.info("Update finance documents vat view mode: found indexes " + indexes.size())

for(FinanceDocumentRecordIndex index : indexes) {

    EntityContainer<FinanceDocument> financeDocumentContainer = EntityStorage.get().resolve(index.getSource())

    if(financeDocumentContainer != null) {

        FinanceDocument financeDocument = financeDocumentContainer.getEntity()

        logger.info("Update finance documents vat view mode: processing finance document " + financeDocument + " (" + financeDocument.getUid() + ")")

        financeDocument.setVatViewMode(mode)

        financeDocumentContainer.getVersionInfo().setDataSource("update-finance-documents-vat-view-mode-script")

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

logger.info("Update finance documents vat view mode: finished")
