package com.bytesw.bytebot.service;

import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Iterator;

@Component("xlsToCsvFileConverter")
public class XlsToCsvFileConverter implements FileConverter {

    private static final String FILE_EXTENSION = ".csv";

    @Value("${application.service.file-converter.xls-to-csv.separator:$$}")
    private String separator;

    @Override
    public byte[] convert(byte[] inputFile, String fileName) {
        StringBuffer data = new StringBuffer();
        InputStream fis = null;
        Workbook workbook = null;

        try {
            //FileOutputStream fos = new FileOutputStream();
            // Get the workbook object for XLSX file
            fis = new ByteArrayInputStream(inputFile);

            String ext = FilenameUtils.getExtension(fileName);

            if (ext.equalsIgnoreCase("xlsx")) {
                workbook = new XSSFWorkbook(fis);
            } else if (ext.equalsIgnoreCase("xls")) {
                workbook = new HSSFWorkbook(fis);
            }

            // Get first sheet from the workbook

            int numberOfSheets = workbook.getNumberOfSheets();
            Row row;
            Cell cell;
            // Iterate through each rows from first sheet

            for (int i = 0; i < numberOfSheets; i++) {
                Sheet sheet = workbook.getSheetAt(0);
                Iterator<Row> rowIterator = sheet.iterator();

                while (rowIterator.hasNext()) {
                    row = rowIterator.next();
                    // For each row, iterate through each columns
                    Iterator<Cell> cellIterator = row.cellIterator();
                    while (cellIterator.hasNext()) {

                        cell = cellIterator.next();

                        switch (cell.getCellType()) {
                            case BOOLEAN:
                                data.append(cell.getBooleanCellValue() + separator);

                                break;
                            case NUMERIC:
                                data.append(cell.getNumericCellValue() + separator);

                                break;
                            case STRING:
                                data.append(cell.getStringCellValue() + separator);
                                break;

                            case BLANK:
                                data.append("" + separator);
                                break;
                            default:
                                data.append(cell + separator);

                        }
                    }
                    data.setLength(data.length() - separator.length());
                    data.append('\n'); // appending new line after each row
                }

            }
            return data.toString().getBytes();
            //fos.write(data.toString().getBytes());
            //fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (Exception e) {}
            }

            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e) {}
            }
        }
        return new byte[]{};
    }

    @Override
    public String getFileName(String fileName) {
        int position = fileName.lastIndexOf(".");
        String fileNameWithoutExtension = fileName.substring(0, position);
        return fileNameWithoutExtension + FILE_EXTENSION;
    }
}
