/*
 * Copyright (C) 2023 favdb
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package storybook.tools.zip;

import java.io.*;
import java.util.zip.*;

/**
 * compressed data file for reading or writing
 *
 * @author favdb
 */
public class ZipData {

	private File file;
	private FileOutputStream fos;
	private BufferedInputStream zipin;
	private FileInputStream fis;
	private DeflaterOutputStream zipout;

	public ZipData() {
		// empty
	}

	public File getFile() {
		return file;
	}

	/**
	 * create the compressed file for writing
	 *
	 * @param filename
	 * @param overwrite
	 * @throws java.io.FileNotFoundException
	 */
	public void create(String filename, boolean overwrite)
			throws FileNotFoundException {
		File f = new File(filename);
		if (f.exists()) {
			if (overwrite) {
				f.delete();
			} else {
				return;
			}
		}
		this.file = f;
		fos = new FileOutputStream(filename);
		Deflater deflater = new Deflater();
		deflater.setLevel(Deflater.BEST_COMPRESSION);
		zipout = new DeflaterOutputStream(fos, deflater);
	}

	/**
	 * open the compressed file for reading
	 *
	 * @param filename
	 * @throws java.io.FileNotFoundException
	 */
	public void open(String filename)
			throws FileNotFoundException {
		File f = new File(filename);
		if (!f.exists()) {
			return;
		}
		this.file = f;
		fis = new FileInputStream(filename);
		zipin = new BufferedInputStream(new InflaterInputStream(fis));
	}

	public void write(String value) throws IOException {
		if (zipout == null) {
			throw new IOException("File was not opened for writing");
		}
		for (char c : value.toCharArray()) {
			zipout.write(c);
		}
		zipout.flush();
	}

	public String read() throws IOException {
		if (zipin == null) {
			throw new IOException("File was not opened for reading");
		}
		StringBuilder b = new StringBuilder();
		while (zipin.available() > 0) {
			byte c = (byte) (zipin.read());
			if (c == '\n') {
				break;
			}
			b.append(c);
		}
		return b.toString();
	}

	public void close() {
		try {
			if (zipin != null) {
				zipin.close();
			}
			if (zipout != null) {
				zipin.close();
			}
		} catch (IOException ex) {
			// empty
		}
	}

}
