package com.gridnine.xtrip.server.reports.prepare.statistics

import com.gridnine.xtrip.common.Environment
import com.gridnine.xtrip.common.model.Xeption
import com.gridnine.xtrip.common.model.support.reports.DetailedProductStatisticsReportContentRequest
import com.gridnine.xtrip.common.model.support.reports.DetailedProductStatisticsReportContentResponse
import com.gridnine.xtrip.common.model.system.Message
import com.gridnine.xtrip.common.model.system.MessageType
import com.gridnine.xtrip.common.util.MiscUtil
import com.gridnine.xtrip.common.util.TextUtil
import com.gridnine.xtrip.common.util.ValueHolder
import com.gridnine.xtrip.server.configuration.ServerConfiguration
import com.gridnine.xtrip.server.model.statistics.CollectStatisticsFlagPublisher
import com.gridnine.xtrip.server.model.synchronization.SynchronizationHelper
import com.gridnine.xtrip.server.model.synchronization.SynchronizationRequest
import com.gridnine.xtrip.server.model.synchronization.SynchronizationResponse

def data = new DetailedProductStatisticsReportContentRequest()
data.startDate = MiscUtil.toLocalDate(parameters.startDate)
data.endDate = MiscUtil.toLocalDate(parameters.endDate)
data.agencies.addAll(parameters.agencies)
data.subagencies.addAll(parameters.subagencies)
String licenseKey = Environment.getPublished(ServerConfiguration.class).getConfiguration().getProperty("licenceKey")
if(TextUtil.isBlank(licenseKey)){
    throw Xeption.forEndUser("в настройках программы не задан лицензионный ключ")
}
def url = CollectStatisticsFlagPublisher.STATISTICS_SERVER_URL
//licenseKey = "2F3DFC12C438A0055D1EA90AD0E890F3F5F29F598958471A"//put test key here
//url = "http://localhost:7070/sync/"//put test url here
data.setLicenceKey(licenseKey)
SynchronizationRequest<DetailedProductStatisticsReportContentRequest> request =
        new SynchronizationRequest<>()
request.setClientId(Environment.getApplicationId())
request.setData(data)
request.setOperationId(DetailedProductStatisticsReportContentRequest.class.getSimpleName())
request.setUser(CollectStatisticsFlagPublisher.STATISTICS_USER)
ValueHolder<String> trace = new ValueHolder<>()

SynchronizationResponse<DetailedProductStatisticsReportContentResponse> response = SynchronizationHelper.execute(request, url, trace)

for(Message msg: response.getMessages()){
    if(msg.type  == MessageType.ERROR){
        throw Xeption.forEndUser(msg.message.toString())
    }
}

def content = response.data.content

reportContent(content)