/*
 *      _______                       _____   _____ _____  
 *     |__   __|                     |  __ \ / ____|  __ \ 
 *        | | __ _ _ __ ___  ___  ___| |  | | (___ | |__) |
 *        | |/ _` | '__/ __|/ _ \/ __| |  | |\___ \|  ___/ 
 *        | | (_| | |  \__ \ (_) \__ \ |__| |____) | |     
 *        |_|\__,_|_|  |___/\___/|___/_____/|_____/|_|     
 *                                                         
 * -------------------------------------------------------------
 *
 * TarsosDSP is developed by Joren Six at IPEM, University Ghent
 *  
 * -------------------------------------------------------------
 *
 *  Info: http://0110.be/tag/TarsosDSP
 *  Github: https://github.com/JorenSix/TarsosDSP
 *  Releases: http://0110.be/releases/TarsosDSP/
 *  
 *  TarsosDSP includes modified source code by various authors,
 *  for credits and info, see README.
 * 
 */

package com.yonge.netty.server.processor;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import be.tarsos.dsp.writer.WaveHeader;

/**
 * 写wav文件
 */
public class WaveformWriter {

	private static final Logger LOGGER = LoggerFactory.getLogger(WaveformWriter.class);

	private RandomAccessFile randomAccessFile;

	private final String fileName;

	public static final short CHANNEL_NUM = 1;

	public static final int SAMPLE_RATE = 44100;

	public static final short BITS_PER_SAMPLE = 16;

	public static final int HEADER_LENGTH = 44;

	public WaveformWriter(String fileName) {

		this.fileName = fileName;
		try {
			randomAccessFile = new RandomAccessFile(fileName, "rw");
			randomAccessFile.write(new byte[HEADER_LENGTH]);
		} catch (IOException e) {
			LOGGER.error("创建WAV文件出现异常[{}]:{}", fileName, e.getMessage());
			e.printStackTrace();
		}

	}

	public boolean process(byte[] datas) {

		try {
			randomAccessFile.write(datas);
		} catch (IOException e) {
			LOGGER.error("写WAV文件出现异常[{}]:{}", fileName, e.getMessage());
			e.printStackTrace();
		}

		return true;
	}

	public void processingFinished() {
		try {
			WaveHeader waveHeader = new WaveHeader(WaveHeader.FORMAT_PCM, CHANNEL_NUM, SAMPLE_RATE, BITS_PER_SAMPLE, (int) randomAccessFile.length()
					- HEADER_LENGTH);

			ByteArrayOutputStream header = new ByteArrayOutputStream();
			waveHeader.write(header);
			randomAccessFile.seek(0);
			randomAccessFile.write(header.toByteArray());
			randomAccessFile.close();
		} catch (IOException e) {
			LOGGER.error("关闭WAV文件出现异常[{}]:{}", fileName, e.getMessage());
			e.printStackTrace();
		}
	}

	public File getFile() {
		return new File(fileName);
	}

	public long getFileLength(boolean isSubHeadLength) {
		try {
			if (isSubHeadLength) {
				return randomAccessFile.length() - HEADER_LENGTH;
			}
			return randomAccessFile.length();
		} catch (IOException e) {
			LOGGER.error("读取WAV文件出现异常[{}]:{}", fileName, e.getMessage());
			e.printStackTrace();
		}
		return 0;
	}
}
