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

import java.text.SimpleDateFormat
import java.util.List

import com.gridnine.xtrip.common.model.EntityContainer
import com.gridnine.xtrip.common.model.entity.EntityStorage
import com.gridnine.xtrip.common.model.finance.ChartOfAccountsSettings
import com.gridnine.xtrip.common.model.finance.FinanceInitializationData
import com.gridnine.xtrip.common.model.finance.FinanceInitializationDataIndex
import com.gridnine.xtrip.common.model.helpers.FinanceHelper
import com.gridnine.xtrip.common.model.profile.OrganizationIndex
import com.gridnine.xtrip.common.search.SearchQuery
import com.gridnine.xtrip.common.search.SearchCriterion.SimpleCriterion

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

SearchQuery query = new SearchQuery()

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

for (OrganizationIndex index : indexes) {

    EntityContainer<ChartOfAccountsSettings> chartOfAccountsSettingsContainer = EntityStorage.get().resolve(FinanceHelper.getChartOfAccountsSettings(index.getSource(), false))

    if (chartOfAccountsSettingsContainer != null) {

        ChartOfAccountsSettings chartOfAccountsSettings = chartOfAccountsSettingsContainer.getEntity()

        if (!FinanceHelper.isChartOfAccountsSettingsDisabled(chartOfAccountsSettings)) {

			query = new SearchQuery()
			
			query.getCriteria().getCriterions().add(SimpleCriterion.eq(FinanceInitializationDataIndex.Property.organization.name(), index.getSource()))

			if(EntityStorage.get().search(FinanceInitializationDataIndex.class, query).getData().size() == 0) {

	            FinanceInitializationData data = new FinanceInitializationData()

    	        data.setOrganization(index.getSource())
        	    data.setDate(new SimpleDateFormat("yyyy.MM.dd HH:mm:ss.SSS").parse("2017.09.01 00:00:00.000"))

            	EntityStorage.get().save(EntityContainer.create(data), true)
            	
				logger.info('FIDCT: data created -> ' + index.getSource())
			}
        }
    }
}
