package com.gridnine.xtrip.server.tasks

import com.gridnine.xtrip.common.model.entity.EntityStorage
import com.gridnine.xtrip.common.search.SearchCriterion
import com.gridnine.xtrip.common.search.SearchQuery
import com.gridnine.xtrip.common.search.SearchResult
import com.gridnine.xtrip.common.model.export.ExportCategory
import com.gridnine.xtrip.common.model.export.BasicExportSettingsIndex
import com.gridnine.xtrip.server.db.storage.LogicalStorage
import com.gridnine.xtrip.server.db.storage.common.LogicalSession
import com.gridnine.xtrip.server.db.storage.hibernate.HibernateSessionManager
import com.gridnine.xtrip.server.db.storage.model.PhysicalStorageSession
import org.hibernate.Session
import org.hibernate.connection.ConnectionProvider
import org.hibernate.engine.SessionFactoryImplementor

import java.sql.Connection
import java.sql.PreparedStatement
import java.util.List

final SearchQuery query = new SearchQuery()
for (ExportCategory category : ExportCategory.values()) {
    query.getCriteria()
        .getCriterions().add(
            SearchCriterion.not(
                SearchCriterion.eq(
                    BasicExportSettingsIndex.Property.exportCategory.name(),
                    category
                )
            )
    )
}

query.getPreferredProperties().add("uid")

SearchResult<BasicExportSettingsIndex> search =
        EntityStorage.get().search(BasicExportSettingsIndex.class, query)

List<BasicExportSettingsIndex> idxs

if (search != null) {
    idxs = search.getData()

    if (idxs == null || idxs.isEmpty()){
        return
    }
    LogicalSession ls = LogicalStorage.get().beginUnitOfWork()
    PhysicalStorageSession ps = ls.getSession()
    Session session = ((HibernateSessionManager.HibernatePhysicalStorageSession) ps).getSession()

    SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) session.getSessionFactory()
    ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider()
    String sql = "DELETE FROM basicexportsettingsindexdata WHERE uid = ?"
    Connection cnn = connectionProvider.getConnection()
    PreparedStatement st = cnn.prepareStatement(sql)
    try {
        cnn.setAutoCommit(true)
        for (BasicExportSettingsIndex idx : idxs) {
            if (idx == null) {
                continue
            }

            st.setString(1, idx.getUid())
            st.executeUpdate()
        }
    } finally {
        if (st != null && !st.isClosed()) {
            st.close()
        }
    }
}