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

import com.hybris.cockpitng.annotations.SocketEvent;
import com.hybris.cockpitng.util.DefaultWidgetController;
import de.hybris.platform.core.model.BraintreePluginConfigurationModel;
import de.hybris.platform.servicelayer.impex.ImportConfig;
import de.hybris.platform.servicelayer.impex.ImportResult;
import de.hybris.platform.servicelayer.impex.ImportService;
import de.hybris.platform.servicelayer.impex.impl.StreamBasedImpExResource;
import org.apache.log4j.Logger;
import org.zkoss.util.media.Media;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.BindContext;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Messagebox;


import java.nio.charset.StandardCharsets;

public class BraintreeImportConfigurationController extends DefaultWidgetController {

    private static final String IN_SOCKET = "inputObject";
    private static final String ZIP = "zip";
    private static final String UPLOAD_FILE_TITLE = "Upload file";
    private static final String APPLY_CONFIGURATION_TITLE = "Apply the configurations";
    private static final String IMPORT_CONFIGURATION_MESSAGE = "Are you sure you want to import the configurations to the system from this file?";
    private static final String CONFIGURATION_APPLIED_MESSAGE = "The configuration was successfully applied";
    private static final String WRONG_EXTENSION_ERROR = "Please, upload the file with .zip extension";
    private static final String GENERAL_ERROR = "An error occurred during applying the configuration. Please try again later!";

    @WireVariable
    private ImportService importService;


    @Command
    public void onFileUpload(@ContextParam(ContextType.BIND_CONTEXT) BindContext ctx) {
        Object triggerEvent = ctx.getTriggerEvent();
        if (!(triggerEvent instanceof UploadEvent)) {
            return;
        }

        UploadEvent uploadEvent = (UploadEvent) triggerEvent;

        if (!isMediaInZipExtension(uploadEvent)) {
            createWrongExtensionMessage();
            return;
        }

        createApplyConfigurationPopup(uploadEvent);
    }

    protected void createWrongExtensionMessage() {
        Messagebox.show(WRONG_EXTENSION_ERROR, UPLOAD_FILE_TITLE, Messagebox.OK, Messagebox.ERROR);
    }

    protected void createApplyConfigurationPopup(UploadEvent uploadEvent) {
        Media media = uploadEvent.getMedia();
        Messagebox.show(IMPORT_CONFIGURATION_MESSAGE, APPLY_CONFIGURATION_TITLE,
                Messagebox.YES | Messagebox.NO, Messagebox.QUESTION,
                event -> {
                    if (!Messagebox.ON_YES.equals(event.getName())) {
                        return;
                    }
                    ImportResult result = importService.importData(createImportConfig(media));
                    if (result.isSuccessful() && !result.isError()) {
                        Messagebox.show(CONFIGURATION_APPLIED_MESSAGE,
                                APPLY_CONFIGURATION_TITLE, Messagebox.OK, Messagebox.INFORMATION);
                    } else {
                        Messagebox.show(GENERAL_ERROR,
                                APPLY_CONFIGURATION_TITLE, Messagebox.OK, Messagebox.ERROR);
                    }
                });
    }

    protected boolean isMediaInZipExtension(UploadEvent uploadEvent) {
        Media media = uploadEvent.getMedia();
        return media.getFormat().equals(ZIP);
    }

    private ImportConfig createImportConfig(Media media) {
        ImportConfig importConfig = new ImportConfig();
        importConfig.setScript(new StreamBasedImpExResource(media.getStreamData(), StandardCharsets.UTF_8.name()));
        return importConfig;
    }

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