package de.thpeetz.kontor.data.views;

import com.vaadin.flow.component.checkbox.Checkbox;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.spring.annotation.SpringComponent;
import de.thpeetz.kontor.common.views.MainLayout;
import de.thpeetz.kontor.data.services.DataManagementService;
import jakarta.annotation.security.PermitAll;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;

import java.io.File;

@Slf4j
@SpringComponent
@Scope("prototype")
@PermitAll
@Route(value = "common/import", layout = MainLayout.class)
@PageTitle("Import Data | Kontor")
public class DataManagementView extends VerticalLayout {

    DataManagementService service;

    public DataManagementView(DataManagementService service) {
        this.service = service;
        File uploadFolder = getUploadFolder();
        UploadArea uploadArea = new UploadArea(uploadFolder);
        Checkbox pruneTables = new Checkbox("Prune Table");
        ImportArea importArea = new ImportArea(uploadFolder, pruneTables, service);

        uploadArea.getUploadField().addSucceededListener(e -> {
            uploadArea.hideErrorField();
            importArea.processFiles();
            uploadArea.getUploadField().clearFileList();
        });

        add(uploadArea, pruneTables, importArea);
    }

    private File getUploadFolder() {
        File folder = new File("uploaded-files");
        if (!folder.exists()) {
            folder.mkdirs();
        }
        return folder;
    }
}
