package com.gridnine.xtrip.server.reports.templates

import com.gridnine.xtrip.common.model.asset.AssetsStorage
import com.gridnine.xtrip.common.model.assets.Workspace
import com.gridnine.xtrip.common.search.SearchQuery
import com.gridnine.xtrip.common.search.SearchCriterion
import com.gridnine.xtrip.common.Environment
import com.gridnine.xtrip.common.meta.MetaRegistry
import com.gridnine.xtrip.common.xml.XUtil
import com.gridnine.xtrip.common.search.ResultMode
import com.gridnine.xtrip.common.model.entity.EntityStorage
import com.gridnine.xtrip.common.model.profile.PersonIndex
import groovy.transform.Field

createStyle(name: 'textData', h_alignment: 'CENTER', v_alignment: 'BOTTOM', leftBorder:'THIN', rightBorder:'THIN', topBorder:'THIN', bottomBorder:'THIN', 'wrapText' : true)
createStyle(name: 'numberData', parent: 'textData', h_alignment: 'RIGHT')

switchPage('source')
moveTo(0, 0)

@Field int maxTriesNumber = 5

tickets { PersonIndex personInd ->
    SearchQuery sq = new SearchQuery()
    sq.criteria.criterions.add(SearchCriterion.eq('owner', personInd.loginName))
    sq.preferredProperties.add('uid')
    sq.limit = 1
    
    def data = AssetsStorage.get().search(Workspace.class, sq, true).data
    
    data.each {
        Workspace workspace = AssetsStorage.get().load(Workspace.class, it.uid, true)
        workspace.repositories.each {
            getFolders(it.folders).each { folder ->
                def idxclass = folder.customData['index-class']
                def squery = folder.customData['query']
                cleanQuery(squery, idxclass)
                squery.filters?.each { filter ->
                    def category = getCategory(idxclass, filter.property)
                    if (category) {
                        def clonesquery = XUtil.clone(squery)
                        clonesquery.resultMode = ResultMode.DATA_ONLY
                        clonesquery.limit = 1
                        clonesquery.filters.clear()
                        clonesquery.filters.add(filter)
                        long timing
                        def sr
                        boolean succeed = false
                        try {
                            long startTime = System.currentTimeMillis()
                            sr = EntityStorage.get().search(Class.forName(idxclass), clonesquery)
                            timing = System.currentTimeMillis() - startTime
                            succeed = true
                        } catch (Exception e) {
                            warn ("exc: ${e.getMessage()}")
                        }
                        int count
                        if (succeed) {
                            count = sr.getFilter(filter.property).size()
                        } else {
                            count = -1
                        }
                        
                        nextRow()
                        text(workspace.owner, 'textData')
                        
                        nextColumn()
                        text(folder.name, 'textData')
                        
                        nextColumn()
                        text(category, 'textData')
                        
                        nextColumn()
                        number(timing, 'numberData')
                        
                        nextColumn()
                        number(count, 'numberData')
                    }
                }
            }
        }
    }
}

int endRowIndex = getRowIndex()
namedRange('listSource', "source!\$A\$1:\$E\$${endRowIndex + 1}")

def cleanQuery(def squery, def idxclass) {
    def indexes = Environment.getPublished(MetaRegistry.class).getIndexes()
    def index = indexes.get(idxclass)
    def properties = index.properties
    def collections = index.collections
    squery.preferredProperties.removeAll {
        !properties.containsKey(it) && !collections.containsKey(it)
    }
}

def getCategory(def idxclass, def propertyname) {
    def indexes = Environment.getPublished(MetaRegistry.class).getIndexes()
    def index = indexes.get(idxclass)
    def properties = index.properties
    def property = properties.get(propertyname)
    if (property) {
        return property.displayName
    }
    def collections = index.collections
    def collection = collections.get(propertyname)
    return collection?.displayName
}

def getFolders(def folders) {
    def result = new LinkedList()
    result.addAll(folders)
    folders.each {
        result.addAll(getFolders(it.subFolders))
    }
    return result
}