package bass;

import java.util.ArrayList;
import java.util.List;

import com.sun.jna.Memory;
import com.sun.jna.Pointer;

import bass.BassLibrary.BASS_DEVICEINFO;
import bass.BassLibrary.RECORDPROC;
import lombok.Getter;


public abstract class basicfunctions {
	
	abstract public boolean FileConvert(String sourcefilename, int targetsamplingrate, String targetfilename);
	abstract public int OpenFileForStreaming(int playdevice, String sourcefilename, int targetsamplingrate);
	abstract public int OpenInputForStreaming(int recdevice, int targetsamplingrate);
	//used in BASS_Init
	protected final int devinit_freq;
	protected final int devinit_flag;
		
	public basicfunctions(int init_freq, int init_flag) {
		this.devinit_freq = init_freq;
		this.devinit_flag = init_flag;
	}
	
	/**
	 * Stop/Close Input For Streaming
	 * @param rechandle
	 * @return true if Input can be stopped
	 */
	public boolean CloseInputForStreaming(int rechandle) {
		if (BassLibrary.BASS.BASS_ChannelFree(rechandle)) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * BASS_Init dengan devinit_freq dan devinit_flag
	 * @param device playback device start from 0=no sound, 1=first real device
	 * @return true if playback device inited or already inited
	 */
	private boolean BassInit(int device) {
		if (!BassLibrary.BASS.BASS_Init(device, devinit_freq, devinit_flag)) {
			// ada gagal init, cek dulu
			int err = BassLibrary.BASS.BASS_ErrorGetCode();
			if (err!=BassLibrary.Constant.BASS_ERROR_ALREADY) {
				// gak boleh gagal
				//raise_log(BassLibrary.BASS.GetBassError("BASS_Init", err));
				return false;
			}
		} 
		// sampe sini sukses
		return true;
	}
	
	
	/**
	 * BASS_RecordInit
	 * @param device recorder device, start from 0=first real device
	 * @return true if recording device inited or already inited
	 */
	private boolean RecordInit(int device) {
		if (!BassLibrary.BASS.BASS_RecordInit(device)) {
			// ada gagal init, cek dulu
			int err = BassLibrary.BASS.BASS_ErrorGetCode();
			if (err!=BassLibrary.Constant.BASS_ERROR_ALREADY) {
				// gak boleh gagal
				//raise_log(BassLibrary.BASS.GetBassError("BASS_RecordInit", err));
				return false;
			}
		}
		return true;
	}
	
	/**
	 * OpenInput helper
	 * @author rdkartono
	 *
	 */
	protected class OpenInput{
		private final int recorderdev;
		private final @Getter int samplingrate;
		private boolean success = false;
		private String[] errorlist;
		private int recordhandle=0;
		private final RECORDPROC recproc;
		private @Getter BASS_DEVICEINFO devinfo;
		
		public String[] getErrorlist() {
			return errorlist;
		}
		
		public int getRecorderdev() {
			return recorderdev;
		}
		
		public int getRecordhandle() {
			return recordhandle;
		}
		
		public boolean isSuccess() {
			return success;
		}
		
		/**
		 * Open Input 
		 * @param dev 0 = real device
		 * @param samplingrate sampling rate
		 * @param proc RECORDPROC to receive PCM data
		 */
		public OpenInput(int dev, int samplingrate, RECORDPROC proc) {
			this.recorderdev = dev;
			this.samplingrate = samplingrate;
			this.recproc = proc;
			errorlist = OpenSequence();
			
		}
		
		private String[] OpenSequence() {
			
			List<String> error = new ArrayList<String>();
			if (RecordInit(recorderdev)) {
				devinfo = new BASS_DEVICEINFO();
				if (!BassLibrary.BASS.BASS_RecordGetDeviceInfo(recorderdev, devinfo)) devinfo = null;
				Pointer user = null;
				if (devinfo!=null) {
					user = new Memory(devinfo.name.length()+1);
					user.setString(0, devinfo.name);
				}
				
				recordhandle = BassLibrary.BASS.BASS_RecordStart(samplingrate, 1, BassLibrary.Constant.BASS_RECORD_PAUSE, recproc, user);
				if (recordhandle!=0) {
					success = true;
				} else error.add(BassLibrary.BASS.GetBassError("BASS_RecordStart"));
			} else error.add(BassLibrary.BASS.GetBassError("BASS_RecordInit"));
			
			return error.toArray(new String[0]);
		}
		
		public Pointer PointerToDeviceName() {
			if (devinfo==null)
				return null;
			else {
				Pointer pp = new Memory(devinfo.name.length()+1);
				pp.setString(0, devinfo.name);
				return pp;
			}
		}
		
		public String getDeviceName() {
			return devinfo==null ? "" : devinfo.name;
		}
		
		/**
		 * Start Recording
		 * @return error messages if available
		 */
		public String[] StartRecord() {
			List<String> error = new ArrayList<String>();
			if (recordhandle!=0) {
				if (BassLibrary.BASS.BASS_ChannelStart(recordhandle)) {
					// nothing...
				} else error.add(BassLibrary.BASS.GetBassError("BASS_ChannelStart"));
			} else error.add("RecordHandle is zero");
			
			return error.toArray(new String[0]);
		}
		
		/**
		 * Stop Recording
		 * @return error messages if available
		 */
		public String[] StopRecord() {
			List<String> error = new ArrayList<String>();
			if (recordhandle!=0) {
				if (BassLibrary.BASS.BASS_ChannelFree(recordhandle)) {
					// nothing...
				} else error.add(BassLibrary.BASS.GetBassError("BASS_ChannelStop"));
				recordhandle = 0;
			} else error.add("RecordHandle is zero");
			
			return error.toArray(new String[0]);
		}
	}
	
	/**
	 * OpenFile helper
	 * @author rdkartono
	 *
	 */
	protected class OpenFile{
		private final @Getter int playbackdev;
		private final @Getter int samplingrate;
		private final @Getter String filename;
		private final @Getter boolean decodingonly;
		private boolean success = false;
		private int filehandle;
		private int mixerhandle;
		private int mixerflag;
		private String[] errorlist;
		private @Getter long ByteSize;
		private @Getter double Duration;
		private @Getter BASS_DEVICEINFO devinfo;
		
		public String[] getErrorlist() {
            return errorlist;
		}
		
		public int getFilehandle() {
			return filehandle;
		}
		
		public int getMixerhandle() {
			return mixerhandle;
		}
		
		public boolean isSuccess() {
			return success;
		}
		
		
		
		/**
		 * Create OpenFile object
		 * @param filename source file name
		 * @param playbackdev 0 =no sound, 1 = real device
		 * @param samplingrate sampling rate
		 * @param decodingonly if true, mixer will have Decode flag
		 */
		public OpenFile(String filename, int playbackdev, int samplingrate, boolean decodingonly) {
			this.playbackdev = playbackdev;
			this.samplingrate = samplingrate;
			this.filename = filename;
			this.decodingonly = decodingonly;
			this.errorlist = OpenSequence();
			if (success) {
				ByteSize = BassLibrary.BASS.BASS_ChannelGetLength(filehandle, BassLibrary.Constant.BASS_POS_BYTE);
				Duration = BassLibrary.BASS.BASS_ChannelBytes2Seconds(filehandle, ByteSize);
				
			}
			devinfo = new BASS_DEVICEINFO();
			if (!BassLibrary.BASS.BASS_GetDeviceInfo(playbackdev, devinfo)) {
				devinfo = null;
			} 
	
		}
		
		public Pointer PointerToDeviceName() {
			if (devinfo==null)
				return null;
			else {
				Pointer pp = new Memory(devinfo.name.length()+1);
				pp.setString(0, devinfo.name);
				return pp;
			}
		}
		
		public String getDeviceName() {
			return devinfo==null ? "" : devinfo.name;
		}
		
		/**
		 * Create OpenFile Object
		 * @param filename source file anme
		 * @param playbackdev 0 = no sound, 1 = real device
		 * @param samplingrate samplingrate
		 */
		public OpenFile(String filename, int playbackdev, int samplingrate) {
			this(filename, playbackdev, samplingrate, false);
		}
		
		private String[] OpenSequence() {
			
			List<String> error = new ArrayList<String>();
			
			if (BassInit(playbackdev)) {
				
				filehandle = BassLibrary.BASS.BASS_StreamCreateFile(filename, 0, 0, BassLibrary.Constant.BASS_STREAM_DECODE);
				if (filehandle!=0) {
					mixerflag = decodingonly ? BassLibrary.Constant.BASS_STREAM_DECODE : 0;
					
					mixerhandle = BassMixLibrary.BASSMIX.BASS_Mixer_StreamCreate(samplingrate, 1, mixerflag);
					if (mixerhandle!=0) {
						if (BassMixLibrary.BASSMIX.BASS_Mixer_StreamAddChannel(mixerhandle, filehandle, BassLibrary.Constant.BASS_STREAM_AUTOFREE)) {
							success = true;
						} else error.add(BassLibrary.BASS.GetBassError("BASS_Mixer_StreamAddChannel"));
					} else error.add(BassLibrary.BASS.GetBassError("BASS_Mixer_StreamCreate"));
				} else error.add(BassLibrary.BASS.GetBassError("BASS_StreamCreateFile"));
			} else error.add(BassLibrary.BASS.GetBassError("Bass_Init"));
			
			return error.toArray(new String[0]);
		}
		
		/**
		 * Start Playback
		 * @return true if can be started
		 */
		public boolean StartPlayback() {
			if (filehandle!=0) {
				// file sudah kebuka
				if (mixerhandle!=0) {
					// mixer sudah kebuka
					if (success) {
						// sudah plugged in 
						if (!decodingonly) {
							// bukan channel decoding
							return BassLibrary.BASS.BASS_ChannelStart(filehandle);
						}
					}
					
				}
			}
			return false;
		}
		
		/**
		 * Close Opened handles
		 * @return array of string containing error messages
		 */
		public String[] CloseHandles() {
			List<String> error = new ArrayList<String>();
			
			if (filehandle!=0) {
				if (success) {
					// sudah plug ke mixer
					if (!BassMixLibrary.BASSMIX.BASS_Mixer_ChannelRemove(filehandle)) {
						error.add(BassLibrary.BASS.GetBassError("BASS_Mixer_ChannelRemove"));
					}
				}
				if (!BassLibrary.BASS.BASS_ChannelFree(filehandle)) {
					error.add(BassLibrary.BASS.GetBassError("BASS_ChannelFree"));
				}
				
				filehandle = 0;
			}
			if (mixerhandle!=0) {
				if (!BassLibrary.BASS.BASS_ChannelFree(mixerhandle)) {
					error.add(BassLibrary.BASS.GetBassError("BASS_ChannelFree"));
				}
				mixerhandle = 0;
			}
			
			return error.toArray(new String[0]);
		}
	}
}
