<?php
class SpecialList{
	function maker($speciallist, $a){
		if($speciallist[result]!='fail'){
			$a[username] = 'rose@citech.kr';
			$userno = query('select no from info where username=:username', $a);
			$a[user_no] = $userno[0][no];

			$exist = query('select * from playlist where username=:username and title=:title', $a);
			
			// 1.해당 이름의 플레이리스트가 이미 존재하나 확인 
			if(empty($exist)){
				// 없으면 새로 만들기 
				$result = query("
				insert into playlist set 
					username=:username,
					user_no=:user_no, 
					title=:title,
					toshare=1
				", $a);	
				$a[no] = $result[lastInsertId];
				$a[playlistno] = $result[lastInsertId];
				$tag = new Tag();
				$tag->addTagToPlaylist($a);				
			}else{
				// 이미 있으면 기존 플레이리스트 no 가져옴 
				$a[playlistno] = $exist[0][no];				
			}	
			
			// 인기순인 경우, 트랙 전체 지운다음 다시 insert해주는 스케줄이 필요함 
			
			foreach($speciallist[tracks] as $track){
				$a[playurl] = 'https://www.youtube.com/watch?v='.$track[videoid];
				$a[snippet] = json_encode($track[snippet], JSON_UNESCAPED_UNICODE);
				$a[contentDetails] = json_encode($track[contentDetails], JSON_UNESCAPED_UNICODE);
				$a[statistic] = json_encode($track[statistic], JSON_UNESCAPED_UNICODE);
				$a[title] = $track[title];
				$exist_track = query('select no from track where playurl=:playurl and user_no=:user_no and playlistno=:playlistno', $a);
				if(empty($exist_track)){
					// 없으면 추가 
					$result = query("
						insert into track set 
							user_no=:user_no, 
							title=:title,
							playurl=:playurl,
							playlistno=:playlistno,
							snippet=:snippet,
							contentDetails=:contentDetails,
							statistic=:statistic", $a);
				}else{	
					// 있으면 업데이트 	
					$result = query("
						update track set 
							snippet=:snippet,
							contentDetails=:contentDetails,
							statistic=:statistic
						where
							playurl=:playurl and 
							user_no=:user_no
						", $a);	
				}	
			}
			if($result[numAffected]==1)		
				$r[result] = 'success';
		}else{
			$r[result] = 'fail';
			$r[msg] = $speciallist[msg][error][message];
		}
		return $r;
	}
	function getplaylist($a){
		if(!$a[type])
			$a[type] = 'youtube';
		$data = array(
			'username' => $a[username],
			'title' => $a[title],
			'type' => $a[type]
		);
		$url = "http://roseapi.modtv.co.kr/playlist/fetch?". http_build_query($data, '');
		//$url = "http://10.0.0.35/new/apiroot/rose_user/playlist/fetch?". http_build_query($data, '');
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		$res = curl_exec($ch);
		curl_close($ch);
		print_r($res);		
	}
}	 
/*
	
	@param
	name = 미리 정해진 카테고리 입력! 
	1. 시대별작곡가
	2. 인기순 
	
*/

$app->action('speciallist/composer', function() use($auth){
	$a = $_REQUEST;
	$speciallist = new SpecialList;
	$youtubeV3 = new YoutubeV3;
	$a[type] = 'video';
	$a[tags] = $a['era'];
	$a[title] = $a[composer];
	$composer= $youtubeV3->search(preg_replace("/\s+/", "", $a[composer]), "relevance" ,$a[type], 10);
	reply_json($speciallist->maker($composer, $a));	

});	
/*
	youtube playlist id, title 로 specaillist(playlist) CREATE, GET 할 수 있는 API
	1. 존재하지 않은 PLAYLIST 면 새로 생성
	2. 이미 생성한 PLAYLIST라면 가져오기만 함 
*/
$app->action('speciallist/get', function() use($auth){
	$a = $_REQUEST;
	$playlist = new Playlist;
	$speciallist = new SpecialList;
	$youtubeV3 = new YoutubeV3;
	$a[username] = 'rose@citech.kr';
	// 수동 갱신하는 flag 추가 reset = 1인 경우에만 수동 갱신함 
	if(isset($a['reset']) && $a['reset'] == 1)
		$result = query('delete from playlist where username=:username and title=:title', $a);	
	
	$exist = query('select * from playlist where username=:username and title=:title', $a);
	// 있으면 그대로 가져오기 
	if(!empty($exist)){
		$a[playlistno] = $exist[0][no];
		$p = query('select count(*) as totalcount from track where playlistno=:playlistno', $a);
		
		//if 기존 maxResults != new maxResults then playlist refresh  
		if($a[maxResults] && ($p[0][totalcount] != $a[maxResults])){
			$result = query('delete from playlist where username=:username and title=:title', $a);	
			$list = $youtubeV3->getPlaylistItem($a[playlistid] , $a[maxResults]);
			$result = $speciallist->maker($list, $a);
			if($result[result] = 'success')
				$speciallist->getplaylist($a);
		}else{
			$speciallist->getplaylist($a);	 //기존 playlist return 			
		}
	}else{
		// 없으면 새로 만들기 
		if($a[maxResults])
			$list = $youtubeV3->getPlaylistItem($a[playlistid] , $a[maxResults]);
		else
			$list = $youtubeV3->getPlaylistItem($a[playlistid]);
		$result = $speciallist->maker($list, $a);
		if($result[result] = 'success')
			$speciallist->getplaylist($a);
	}
});	

/*
$app->action('speciallist/update', function() use($auth){
	$a = $_REQUEST;
	$playlist = new Playlist;
	$speciallist = new SpecialList;
	$youtubeV3 = new YoutubeV3;
	$a[username] = 'rose@citech.kr';
	if($a[maxResults])
		$list = $youtubeV3->getPlaylistItem($a[playlistid] , $a[maxResults]);
	else
		$list = $youtubeV3->getPlaylistItem($a[playlistid]);
	$speciallist->maker($list, $a);
});	
*/

/*
	최근제생로즈튜브
	트랙no
	username
	limit 100개 
*/
$app->action('speciallist/history/add', function() use($auth){
	$a = $_REQUEST;
	$track= new Track;
	if(!$a[username]){
		reply_json(response(506));
		return;
	}else{
		$info = query('select no from info where username=:username', $a);
		if(!empty($info)){
			$a[user_no] = $info[0][no];
		}else{
			reply_json(response(404));
			return;
		}	
	}	
	if(!$a[type])
		$a[type] = 'youtube';
	// 기본 플레이리스트 (최근에 들은 곡) 없으면 생성 
	if(!$a[mac])
		$a[title] = 'Recently Played Songs';
	else
		$a[title] = $a[mac].'_Recently Played Songs';
	
	$result = query('INSERT INTO playlist (title, username, user_no, type) 
		SELECT :title, :username, :user_no, :type FROM DUAL
		WHERE NOT EXISTS 
		(SELECT * FROM playlist WHERE title=:title and username=:username)', $a);
		
	$p = query('select no from playlist where title=:title and username=:username', $a);	
	$t = $track->get($a[trackno]);
	
	if(!empty($result) && !empty($p[0]) && !empty($t[no])){
		$a[playlistno] = $p[0][no];
		$a[title] = $t[title];
		$a[playurl] = $t[playurl];
		if($t[user_no] == $a[user_no]){
			$a[star] = $t[star];
			$a[favorites] = $t[favorites];
		}
		/* max: 100 개, 넘으면 오래된 track 부터 삭제됨 */
		
		$r=query('delete from track 
		where no NOT IN 
		(select * from (select no from track where playlistno=:playlistno order by creationtime desc limit 99) as temp)
		and playlistno=:playlistno', $a);
		
		$track->insert($a);	
		
	}else{
		reply_json(response(204));
	}
});	

/*
	최근제생로즈튜브
	트랙no
	username
	limit 100개 
*/
$app->action('speciallist/history/get', function() use($auth){
	$a = $_REQUEST;
	$speciallist= new SpecialList;
	if(!$a[username]){
		reply_json(response(506));
		return;
	}else{
		$info = query('select no from info where username=:username', $a);
		if(!empty($info)){
			$a[user_no] = $info[0][no];
		}else{
			reply_json(response(404));
			return;
		}	
	}	
	// 기본 플레이리스트 (최근에 들은 곡) 없으면 생성 
	if(!$a[type]){
		$a[title] = 'Recently Played Songs';
		$speciallist->getplaylist($a);
	}else{
		if($a[mac]){
			$a[title] = $a[mac].'_Recently Played Songs';
			$speciallist->getplaylist($a);
		}else{
			reply_json(506);
			return;
		}	
	}	
});

/*
	새로 생성하고 업데이트 - 이건 고민을 좀 해봄.. 
*/
$app->action('speciallist/popular/delete', function() use($auth){
	$a = $_REQUEST;
	$a[title] = "KPOP TOP 10";
	$a[username] = 'rose@citech.kr';
	$result = query('delete from playlist where title=:title and username=:username', $a);
	if($result[numAffected]){
		echo '[]';
	}
});	


?>