<?php
class Track {
	function makeDefaultTrack($a){
		$t[no] = $a[no];
		$t[user_no] = $a[user_no];
		$t[album_no] = $a[album_no];
		$t[playlistno] = $a[playlistno];
		$t[trackno] = $a[trackno];
		$t[title] = $a[title];
		$t[artist] = $a[artist];
		$t[playurl] = $a[playurl];
		$t[playtime] = $a[playtime];
		$t[is_title_track] = $a[is_title_track];
		$t[songwriter_no] = $a[songwriter_no];
		$t[favorites] = $a[favorites];
		$t[star] = $a[star];
		$t[rank] = $a[rank];
		$t[comment] = $a[comment];
		$t[snippet] = json_decode($a[snippet]);
		$t[contentDetails] = json_decode($a[contentDetails]);
		$t[statistic] = json_decode($a[statistic]);
		$t[creationtime] = $a[creationtime];
		$result = $t;
		return $result;
	}
	public function get($no){
		$r = query("select * from track where no=$no");
		if(isset($r[0])){
			$result=$this->makeDefaultTrack($r[0]);
		}else{
			$result = "[]";
		}
		return $result;
	}

	function insert($a){
		if(!$a[playlistno] || !$a[playurl]){
			reply_json(response(506));
			return;
		}
		if($a[username]){
			$userno = query('select no from info where username=:username', $a);
			$a[user_no] = $userno[0][no]; 
		}		
		if(!$a[favorites])
			$a[favorites] = 0;
		if(!$a[star])
			$a[star] = 0;
		if(!$a[rank])
			$a[rank] = 0;
		$result = query("
			insert into track set 
				user_no=:user_no, 
				album_no=:album_no, 
				trackno=:trackno, 
				title=:title,
				artist=:artist,
				playurl=:playurl,
				playtime=:playtime,
				is_title_track=:is_title_track,
				lyrics=:lyrics,
				songwriter_no=:songwriter_no,
				favorites=:favorites,
				star=:star,
				rank=:rank,
				comment=:comment,
				playlistno=:playlistno
			", $a);
		$a[no] = $result[lastInsertId];	
		
		parse_str(parse_url($a[playurl])[query], $params);	
		if($params[v]){
			// 현재 전체 트랙에서 url 존재하나 확인함 
			$existing_track = query("select title, snippet, contentDetails, statistic from track where playurl=:playurl", $a);
			if($existing_track[1]){
				$a[title] = $existing_track[0][title];
				$a[snippet]= $existing_track[0][snippet];
				$a[contentDetails]= $existing_track[0][contentDetails];
				$a[statistic]= $existing_track[0][statistic];
				$result = query("
					update track set
						title=:title,
						snippet=:snippet,
						contentDetails=:contentDetails, 
						statistic=:statistic
					where no=:no", $a);					
				
			}else{
				$number = $a[no];
				$youtubev3 = new YoutubeV3();
				$a = $youtubev3->getVideo($params[v]);
				$a[no] = $number;
				if($a[result] == 'success'){
					$a[snippet]= json_encode($a[snippet], JSON_UNESCAPED_UNICODE);
					$a[contentDetails]= json_encode($a[contentDetails], JSON_UNESCAPED_UNICODE);
					$a[statistic]= json_encode($a[statistic], JSON_UNESCAPED_UNICODE);
					$result = query("
						update track set
							title=:title,
							snippet=:snippet,
							contentDetails=:contentDetails, 
							statistic=:statistic
						where no=:no", $a);				
				}
			}
		}
		reply_json($this->get($a[no]));		
	}
	function updatePlaylistUpdateTime($playlistno){
		query('update playlist set updatetime=now() where no='.$playlistno);
	}
}

/**
	track fetch
	1. 사용자
	2. playlist ? 
	3. 이름..? 
	4. 등등.. ?? 
*/
$app->action('playlist/track/fetch', function() use($auth){
	$track = new Track();
	$a = $_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	$authorized['status'] = 'OK';
	if($authorized['status'] == 'OK'){	
		if(isset($a[range_start]) && isset($a[range_end]))
			$range = ' limit '.$a[range_end].' offset '.$a[range_start];
		
		if(isset($a[playlistno]))
			$condition = $condition.' and playlistno in ('.$a[playlistno].') ';
		
		if(isset($a[no])){
			$a[trackno] = $a[no];
			$condition = $condition.' and no=:no';
		}	
		if(isset($a[user_no]))
			$condition = $condition.' and user_no=:user_no';	
		if(isset($a[username])){
			$userno = query('select no from info where username=:username', $a);
			$a[user_no] = $userno[0][no]; 	
			$condition = $condition.' and user_no=:user_no';
		}	
		if(isset($a[playurl]))
			$condition = $condition.' and playurl=:playurl';

		$tracks=query("
			select *, (select count(*) from track where 1 ".$condition." and snippet is not null) as totalcount
		    from track 
			where 
				1 ".$condition." and snippet is not null 
			order by rank asc".$range, $a);
			
		if($a[old_version]!=1){
			if(!empty($tracks)){
				$tag = new Tag();
				if(!isset($a[playlistno]) || strpos($a[playlistno], ',') == true)
					$a[playlistno] = $tracks[0][playlistno];
				$all[tags] = $tag->getTagbyparam($a);	
				$all[totalcount] = $tracks[0][totalcount];
				for($i=0;$i<count($tracks);$i++)
					$trackArr[] = $track->makeDefaultTrack($tracks[$i]);
				
				$all[tracks] = $trackArr;
			}else{
				$all = response(204);
			}
			reply_json($all);
		}else{
			reply_json($tracks);
		}
	}else{
		reply_json($authorized);
	}	
});

$app->action('playlist/track/insert', function() use($auth){
	$track = new Track();
	$a = $_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){	
		$track->insert($a);
	}else{
		reply_json($authorized);
	}		
});

$app->action('playlist/track/delete',function() use($playlist, $auth){
	$a = $_REQUEST; 
	$r = query("delete from track where no=".$a[no]);
	if($r[numAffected]==1)
		echo "[]";
	else
		reply_json(response(404));
});

$app->action('playlist/track/get', function() use($auth){
	$track = new Track();
	$a = $_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){		
		if(!$a[username] && !$a[no] && !$a[playurl]){
			reply_json(response(506));
			return;
		}else{
			if(isset($a[username])){
				$userno = query('select no from info where username=:username', $a);
				$a[user_no] = $userno[0][no]; 
				$condition = 'and user_no=:user_no';
			}
			if(isset($a[playurl]))
				$condition = $condition.' and playurl=:playurl';		
			if(isset($a[no]))
				$condition = 'and no=:no';
			
			$r = query('select * from track where 1 '.$condition, $a);
			
			$count = count($r);
			if($count>0){
				foreach($r as $t){
					$trackArr[] = $track->makeDefaultTrack($t);
				}
				
				$temp_array = array(); 
				$i = 0; 
				$key_array = array(); 
				foreach($trackArr as $val) { 
					if (!in_array($val['playurl'], $key_array)) { 
						$key_array[$i] = $val['playurl']; 
						$temp_array[$i] = $val; 
					} 
					$i++; 
				} 
				$result = $temp_array[0];
			}else{
				$result = response(204);
			}
			reply_json($result);
		}
	}else{
		reply_json($authorized);
	}		
});

$app->action('playlist/track/star', function() use($auth){
	$track = new Track();
	$a = $_REQUEST;
	$authorized = $auth->verify($a[accesskey]);
	if($authorized['status'] == 'OK')
	{
		$user_no = query('select no from info where username=:username', $a);
		$a[user_no] = $user_no[0][no]; 
		
		// 0 ~ 5 점수 까지만 가능하게
		if((0 <= $a[star]) && ($a[star] <= 5))
		{
			$a[title] = "별점 ".$a[star]."점 플레이리스트";		//플레이리스트 이름 설정
			$playlist_no = query('select no from playlist where title=:title and username=:username', $a);	//플레이리스트 no 추출
			$a[playlistno] = $playlist_no[0][no];
			
			if($a[no])
			{
				$playurl = query('select playurl from track where no=:no', $a);	//전체 플레이리스트에 해당 곡이 있는지 체크
				$a[playurl] = $playurl[0][playurl];	//해당 곡에서 playurl 추출
					
				$track_list = query('select no from track where user_no=:user_no and no=:no', $a);	//유저의 플레이리스트에 해당 곡이 있는지 체크
				if($track_list[0])	//있으면 해당 트랙에 별점 추가
				{
					foreach($track_list as $r)
						query('update track set star=:star where user_no=:user_no and no='.$r[no], $a);
				}
				
				$playlist_no_array = query('select no from playlist where title like "%별점%플레이리스트%" and username=:username', $a);	//별점 관련 플레이리스트 전부 호출
				foreach($playlist_no_array as $no)	//별점 관련 플레이리스트에서 해당 곡이 있을 경우 삭제
				{
					$r = query('select no from track where playlistno='.$no[no].' and user_no=:user_no and playurl=:playurl', $a);
					if($r[0])
						query('delete from track where playlistno='.$no[no].' and user_no=:user_no and no='.$r[0][no], $a);
				}
				
				if($a[star]>0)
				{
					$favorites = query('select no, favorites from track where user_no=:user_no and playurl=:playurl', $a);
					if($favorites[0])
					{
						$a[favorites] = $favorites[0][favorites];
						foreach($favorites as $no)
							query('update track set star=:star where no='.$no[no], $a);
					}
					
					$track->insert($a);		//유저의 플레이리스트에 해당 곡 추가 및 별점 추가
				}
			}
			else if($a[playurl])
			{
				$track_list = query('select no from track where user_no=:user_no and playurl=:playurl', $a);	//유저의 플레이리스트에 해당 곡이 있는지 체크
				if($track_list[0])	//있으면 해당 트랙에 별점 추가
				{
					foreach($track_list as $r)
						query('update track set star=:star where user_no=:user_no and no='.$r[no], $a);
				}
				
				$playlist_no_array = query('select no from playlist where title like "%별점%플레이리스트%" and username=:username', $a);	//별점 관련 플레이리스트 전부 호출
				foreach($playlist_no_array as $no)	//별점 관련 플레이리스트에서 해당 곡이 있을 경우 삭제
				{
					$r = query('select no from track where playlistno='.$no[no].' and user_no=:user_no and playurl=:playurl', $a);
					if($r[0])
						query('delete from track where playlistno='.$no[no].' and user_no=:user_no and playurl=:playurl', $a);
				}
				
				if($a[star]>0)
				{
					$favorites = query('select no, favorites from track where user_no=:user_no and playurl=:playurl', $a);
					if($favorites[0])
					{
						$a[favorites] = $favorites[0][favorites];
						foreach($favorites as $no)
							query('update track set star=:star where no='.$no[no], $a);
					}
					
					$track->insert($a);
				}
			}
			else
			{
				//$result[result] = 'fail';
				//$result[msg] = 'Missing parameter';
				reply_json(response(506));
			}
		}else
		{
			//$result[result] = 'fail';
			//$result[msg] = 'star is not valid. (star range : 0~5)';
			reply_json(response(400));
		}
	}else
	{
		reply_json($authorized);
	}
});

$app->action('playlist/track/favorites', function() use($auth){
	$track = new Track();
	$a = $_REQUEST;
	$authorized = $auth->verify($a[accesskey]);
	if($authorized['status'] == 'OK')
	{
		$user_no = query('select no from info where username=:username', $a);
		$a[user_no] = $user_no[0][no]; 
		
		$a[title] = "즐겨찾기 플레이리스트";
		$playlist_no = query('select no from playlist where title=:title and username=:username', $a);
		$a[playlistno] = $playlist_no[0][no];
			
		if($a[no])
		{
			$playurl = query('select playurl from track where no=:no', $a);	//전체 플레이리스트에 해당 곡이 있는지 체크
			$a[playurl] = $playurl[0][playurl];	//해당 곡에서 playurl 추출
			
			
			$r = query('select no from track where playlistno=:playlistno and user_no=:user_no and playurl=:playurl', $a);
			if($r[0])
			{
				query('delete from track where playlistno=:playlistno and user_no=:user_no and playurl=:playurl', $a);

				$no = query('select no from track where user_no=:user_no and playurl=:playurl', $a);
				if($no[0])
				{
					foreach($no as $number)
						query('update track set favorites=0 where no='.$number[no]);
				}
				
				$result[result] = 'success';
				$result[msg] = 'delete from favorites playlist';
				reply_json($result);
			}
			else
			{
				$star = query('select no, star from track where user_no=:user_no and playurl=:playurl', $a);
				if($star[0])
				{
					$a[star] = $star[0][star];
					foreach($star as $no)
						query('update track set favorites=1 where no='.$no[no]);
				}
				
				$a[favorites] = 1;
				$track->insert($a);
			}
		}
		else if($a[playurl])
		{
			$r = query('select no from track where playlistno=:playlistno and user_no=:user_no and playurl=:playurl', $a);
			if($r[0])
			{
				query('delete from track where playlistno=:playlistno and user_no=:user_no and playurl=:playurl', $a);
				
				$no = query('select no from track where user_no=:user_no and playurl=:playurl', $a);
				if($no[0])
				{
					foreach($no as $number)
						query('update track set favorites=0 where no='.$number[no]);
				}
				
				$result[result] = 'success';
				$result[msg] = 'delete from favorites playlist';
				reply_json($result);
			}
			else
			{
				$star = query('select no, star from track where user_no=:user_no and playurl=:playurl', $a);
				if($star[0])
				{
					$a[star] = $star[0][star];
					foreach($star as $no)
						query('update track set favorites=1 where no='.$no[no]);
				}
				
				$a[favorites] = 1;
				$track->insert($a);
			}
		}else
		{
			//$result[result] = 'fail';
			//$result[msg] = 'Missing parameter';
			reply_json(response(506));
		}
	}else
	{
		reply_json($authorized);
	}
});

$app->action('playlist/track/rank', function() use($auth){
	$track = new Track();
	$a = $_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK')
	{
		$playlistno = query('select playlistno from track where no=:no', $a);
		$a[playlistno] = $playlistno[0][playlistno];
		
		$r = query('select no from track where playlistno=:playlistno and rank=:rank', $a);
		if($r[0])
		{
			$numberlist = query('select no from track where playlistno=:playlistno and rank>=:rank', $a);
			foreach($numberlist as $no)
				query('update track set rank=rank+1 where no='.$no[no], $a);
		}
		
		$result = query('update track set rank=:rank where no=:no', $a);
		reply_json($track->get($a[no]));	
	}else{
		reply_json($authorized);
	}	
});

/**
	track crud
*/
$app->action('playlist/track/crud', function() use($auth){
	$track = new Track();
	$a = $_REQUEST;
	$cmd = $_SERVER[REQUEST_METHOD];
	switch($cmd)
	{
	case 'POST':
		$a = file_get_contents('php://input');
		$a = json_decode($a, true);	
		$track->insert($a);
		break;
	case 'PUT':
		$no = get_url_no();
		$a = file_get_contents('php://input');
		$a = json_decode($a, true);
		$params = build_mysql_params(array(
			user_no, album_no, trackno, title, artist, playurl,
			playtime, is_title_track, lyrics, songwriter_no,
			favorites, star, rank, comment, playlistno
		), $a);
		query("update track set $params where no=$no");
		reply_json($track->get($no));	
		$track->updatePlaylistUpdateTime($a[playlistno]);
		break;

	case 'GET':
		reply_json($track->get($a[no]));		
		break;

	case 'DELETE':
		$no = get_url_no();
		$r = query('select playlistno from track where no='.$no);
		if($r[0]){
			$playlistno = $r[0][playlistno];	
			$track->updatePlaylistUpdateTime($playlistno);
		}
		query("delete from track where no=$no");
		echo "[]";
		break;
	}
});	
?>