package cn.edu.whu.boot.collection.service.impl;

import cn.edu.whu.boot.collection.service.ExportWriterService;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.opencsv.exceptions.CsvDataTypeMismatchException;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Optional;

@Service
public class CSVExportWriterService implements ExportWriterService {
    private static final Logger logger = LoggerFactory.getLogger(CSVExportWriterService.class);

    @Override
    public <T> Optional<File> writeToFile(Collection<T> values) {
        try {
            Path path = Files.createTempFile("", ".csv");
            String absPath = path.toString();
            try (Writer writer = new FileWriter(absPath)) {
                StatefulBeanToCsvBuilder<T> builder = new StatefulBeanToCsvBuilder<>(writer);
                StatefulBeanToCsv<T> bw = builder.build();
                bw.write(values.iterator());
            }
            return Optional.of(new File(absPath));
        } catch (IOException | CsvRequiredFieldEmptyException | CsvDataTypeMismatchException e) {
            logger.error(e.getMessage());
            return Optional.empty();
        }
    }
}
