<?php

class Musicbrainz_TrackModel extends Model {
	
	private $_bad_track_names = array(
		'[silence]'
	);
	
	public function getReleaseTracks($releases_ids, $group_by_release = false) {
		if (!is_array($releases_ids)) {
			$releases_ids = array($releases_ids);
		}
		
		$tracks = $this->db->getRows(
			$this->db->q('
				SELECT *
				FROM musicbrainz.bh_track
				WHERE
					release_id IN (\''. implode('\',\'', $releases_ids) .'\')
				ORDER BY
					release_id ASC,
					position ASC
			'),
			'id'
		);
		
		foreach ($tracks as $track_id => $track_info) {
			// Конвертируем миллисекунды в секунды
			$tracks[$track_id]['length'] = round($track_info['length'] / 1000);
		}
		
		if ($group_by_release) {
			$g_tracks = array();
			foreach ($tracks as $track) {
				if (!isset($g_tracks[$track['release_id']])) {
					$g_tracks[$track['release_id']] = array();
				}
				$g_tracks[$track['release_id']][$track['id']] = $track;
			}
			return $g_tracks;
		} else {
			return $tracks;
		}
	}
	
	public function getUniqueReleaseTracks($releases_ids) {
		$tracks = $this->getReleaseTracks($releases_ids, true);
		
		$track_list_unique = array();
		$album_list = array();
		$bonus_list = array();
		
		$first_release = current($tracks);
		
		// Заносим треки из первого релиза в массив основных
		foreach ($first_release as $track_id => $track_info) {
			if (!in_array($track_info['name'], $this->_bad_track_names)) {
				$album_list[$track_id] = $track_info;
				$track_list_unique[] = $this->clearTrackName($track_info['name']);
			}
		}
		
		// Все треки, которые не встречаются на первом релизе заносим в бонусы
		foreach ($tracks as $release_id => $release_tracks) {
			foreach ($release_tracks as $track_id => $track_info) {
				if (
					!in_array($track_info['name'], $this->_bad_track_names) &&
					!in_array($this->clearTrackName($track_info['name']), $track_list_unique)
				) {
					$bonus_list[$track_id] = $track_info;
					$track_list_unique[] = $this->clearTrackName($track_info['name']);
				}
			}
		}
		
		return array(
			'tracks'	=> $album_list,
			'bonus'		=> $bonus_list
		);
	}
	
	private function clearTrackName($name) {
		$name = str_replace('&', 'and', $name);
		preg_match_all('/[a-z0-9]/Ui', $name, $m);
		return strtolower(implode($m[0]));
	}
}