/*
  Copyright [2013-2014] eBay Software Foundation

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package ru.yandex.webmaster3.core.xcelite;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import ru.yandex.webmaster3.core.xcelite.sheet.NotLeakingXceliteSheetImpl;
import ru.yandex.webmaster3.core.xcelite.sheet.XceliteSheet;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author leonidrom
 */
public class NotLeakingXcelite {
    private final int MAX_ROWS_TO_KEEP_IN_MEMORY = 1_000;

    private final Workbook workbook;

    public NotLeakingXcelite() {
        workbook = new SXSSFWorkbook(MAX_ROWS_TO_KEEP_IN_MEMORY);
    }

    /**
     * Creates new sheet with specified name.
     *
     * @param name the sheet name   *
     * @return XceliteSheet object
     */
    public XceliteSheet createSheet(String name) {
        return new NotLeakingXceliteSheetImpl(workbook.createSheet(name), null);
    }

    /**
     * Gets the excel file as byte array.
     *
     * @return byte array which represents the excel file
     */
    public byte[] getBytes() throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (baos) {
            workbook.write(baos);
        } finally {
            workbook.close();
        }

        return baos.toByteArray();
    }

    public void write(OutputStream os) throws IOException {
        try {
            workbook.write(os);
        } finally {
            os.close();
            workbook.close();
        }
    }
}
