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.ProductStatisticsReportContentRequest
import com.gridnine.xtrip.common.model.support.reports.ProductStatisticsReportContentResponse
import com.gridnine.xtrip.common.model.support.reports.ProductStatisticsReportRequest
import com.gridnine.xtrip.common.model.support.reports.ProductStatisticsReportResponse
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 ProductStatisticsReportContentRequest()
data.startDate = MiscUtil.toLocalDate(parameters.startDate)
data.endDate = MiscUtil.toLocalDate(parameters.endDate)
data.splitByMonth = Boolean.TRUE.equals(parameters.splitByMonth);
data.splitBySubagency = Boolean.TRUE.equals(parameters.splitBySubagency);
String licenseKey = Environment.getPublished(ServerConfiguration.class).getConfiguration().getProperty("licenceKey");
if(TextUtil.isBlank(licenseKey)){
    throw Xeption.forEndUser("в настройках программы не задан лицензионный ключ")
}
data.setLicenceKey(licenseKey)
SynchronizationRequest<ProductStatisticsReportContentRequest> request =
        new SynchronizationRequest<>();
request.setClientId(Environment.getApplicationId());
request.setData(data);
request.setOperationId(ProductStatisticsReportContentRequest.class.getSimpleName());
request.setUser(CollectStatisticsFlagPublisher.STATISTICS_USER);
ValueHolder<String> trace = new ValueHolder<>();

SynchronizationResponse<ProductStatisticsReportContentResponse> response = SynchronizationHelper.execute(request, CollectStatisticsFlagPublisher.STATISTICS_SERVER_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)