//	Contour - Android drawing teacher application
//	Copyright (C) 2014  Johannes Riedmann
//	
//	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 com.j0h1.contour.server.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.j0h1.contour.server.DatabaseManager;
import com.j0h1.contour.server.dao.AbstractDAO;
import com.j0h1.contour.server.dao.DAOTrack;
import com.j0h1.contour.server.dao.DAOTrackException;
import com.j0h1.contour.server.rest.pojo.Track;

/**
 * Implementations for DAOTrack.
 * @author Johannes Riedmann
 *
 */
public class DAOTrackImpl extends AbstractDAO implements DAOTrack {
	
	private Connection connection;
	private PreparedStatement prep;
	private DatabaseManager dbm;
	
	public DAOTrackImpl() {
		connection = null;
		prep = null;
		dbm = DatabaseManager.getInstance();
	}

	@Override
	public ArrayList<Track> findAll(String language) throws DAOTrackException {
		openConnection();
		connection = dbm.getConnection();
		
		ArrayList<Track> ret = new ArrayList<Track>();
		
		try {
			prep = connection.prepareStatement("select a.trackId, b.trackname "
					+ "from track a, track_translation b "
					+ "where a.trackid = b.trackid and langcode = ? "
					+ "and deleted = false");
			prep.setString(1, language);
			
			ResultSet tracks = prep.executeQuery();
			
			while(tracks.next()) {
				Track tempTrack = new Track();
				tempTrack.setTrackId(tracks.getInt("trackId"));
				tempTrack.setTrackname(tracks.getString("trackname"));
				
				ret.add(tempTrack);
			}
			
			tracks.close();
			prep.close();
			
			return ret;
		} catch (SQLException e) {
			throw new DAOTrackException("Unable to find tracks.");
		} finally {
			closeConnection();
		}
	}

}
