package com.braintree.customersupportbackoffice.widgets.braintreePluginConfiguration.exportConfiguration;

import com.hybris.cockpitng.annotations.SocketEvent;
import com.hybris.cockpitng.annotations.ViewEvent;
import com.hybris.cockpitng.util.DefaultWidgetController;
import de.hybris.platform.core.model.BraintreePluginConfigurationModel;
import de.hybris.platform.impex.model.ImpExMediaModel;
import de.hybris.platform.servicelayer.impex.ExportConfig;
import de.hybris.platform.servicelayer.impex.ExportResult;
import de.hybris.platform.servicelayer.impex.ExportService;
import de.hybris.platform.servicelayer.impex.impl.ClasspathImpExResource;
import de.hybris.platform.servicelayer.media.MediaService;
import org.apache.log4j.Logger;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.Messagebox;

import javax.annotation.Resource;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class BraintreeExportConfigurationController extends DefaultWidgetController {

    private static final String IN_SOCKET = "inputObject";
    private static final String IMPEX_PATH = "/impex/essentialdataExportBraintreeConfigurations.impex";
    private static final String DOWNLOAD_TITLE = "Download completed";
    private static final String DOWNLOAD_MESSAGE_SUCCESS = "Your export has been downloaded.";

    @Resource(name = "exportService")
    private ExportService exportService;
    @Resource(name = "mediaService")
    private MediaService mediaService;


    @ViewEvent(componentID = "exportConfiguration", eventName = Events.ON_CLICK)
    public void exportConfiguration() {
        ExportResult result = exportService.exportData(createExportConfig());
        executeMediaDownload(result.getExportedData());
    }

    protected ExportConfig createExportConfig() {
        ExportConfig exportConfig = new ExportConfig();
        exportConfig.setScript(new ClasspathImpExResource(IMPEX_PATH, StandardCharsets.UTF_8.name()));
        return exportConfig;
    }

    protected void executeMediaDownload(ImpExMediaModel media) {
        InputStream mediaStream = mediaService.getStreamFromMedia(media);
        String mime = media.getMime();
        String fileName = media.getCode();
        Filedownload.save(mediaStream, mime, fileName);
        Messagebox.show(DOWNLOAD_MESSAGE_SUCCESS,
                DOWNLOAD_TITLE, Messagebox.OK, Messagebox.INFORMATION);
    }

    @SocketEvent(socketId = IN_SOCKET)
    public void initExportConfigurationForm(BraintreePluginConfigurationModel braintreePluginConfigurationModel) { }
}
