/*
 * Disc.java
 *
 * Copyright (c) 2007  Vreixo Formoso
 *
 * This library 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 2 of the License, or
 * (at your option) any later version.
 * See COPYING file for details.
 */

package org.pykix.libburnia.libburn;

import org.pykix.libburnia.bindings.Proxy;

/**
 * References a whole disc.
 * 
 * @author Vreixo Formoso
 * @since 0.1
 */
public class Disc extends Proxy {
	
	public static final int POS_END = 100;

	/**
	 * Create a new disc.
	 */
	public Disc() {
		super( burn_disc_create() );
	}
	
	Disc(long ptr) {
		super(ptr);
	}
	
	/**
	 * Add a session to disc at a specific position.
	 * 
	 * @param session
	 * 		Session to add to the disc.
	 * @param pos
	 * 		position to add at ({@link #POS_END} is "at the end").
	 * @return
	 * 		<code>true</code> on success, <code>false</code> on failure.
	 */
	public boolean addSession(Session session, int pos) {
		
		if ( pos > POS_END ) {
			return false;
		}
		return burn_disc_add_session( pointerOf(this), pointerOf(session), pos);
	}
	
	/**
	 * Remove a session from a disc.
	 * 
	 * @param session
	 * 		Session to find and remove.
	 * @return
	 * 		<code>true</code> on success, <code>false</code> on failure,
	 * 		for example if session was not previously added to disc.
	 */
	public boolean removeSession(Session session) {
		return burn_disc_remove_session( pointerOf(this), pointerOf(session));
	}
	
	/**
	 * Gets an array of all the sessions for the disc.
	 * 
	 * <p>
	 * <b>THIS IS NO LONGER VALID AFTER YOU ADD OR REMOVE A SESSION.</b>
	 * 
	 * FIXME same problem as in {@link Session#getTracks()}
	 * 
	 * @return
	 * 		An array with the sessions.
	 */
	public Session[] getSessions() {
		
		long[] sessionPtrs = burn_disc_get_sessions(pointerOf(this));
		
		Session[] sessions = new Session[sessionPtrs.length];
		
		for ( int i = 0; i < sessionPtrs.length; ++i ) {
			
			long ptr = sessionPtrs[i];
			
			Session session = (Session) proxyFor(ptr);
			if (session == null) {
				session = new Session(ptr);
			}
			sessions[i] = session;
		}
		
		return sessions;
	}
	
	/**
	 * Get how much long the disc will be.
	 *  
	 * @return
	 * 		Number of sectors of the disc.
	 */
	public int getSectors() {
		return burn_disc_get_sectors( pointerOf(this) );
	}
	
	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		burn_disc_free( pointerOf(this) );
	}
	
	private static native long burn_disc_create();
	
	private static native void burn_disc_free(long d);
	
	private static native boolean burn_disc_add_session( long d, long s, 
			int pos);
	
	private static native boolean burn_disc_remove_session(long d, long s);
	
	private static native long[] burn_disc_get_sessions(long d);
	
	private static native int burn_disc_get_sectors(long d);
	
}
