<?php
require 'image.php';
// update playlist p inner join info i on p.user_no = i.no set p.username = i.username

class Playlist {
	function makeDefaultPlaylist($a){
		if(!$a[rank])
			$a[rank] = 0;	
		if(!$a[type])
			$a[type] = 'youtube';
		if(!$a[toshare])
			$a[toshare] = 0;
		if(!$a[isdefault])
			$a[isdefault] = 0;
		$p[no] = $a[no];
		$p[user_no] = $a[user_no];
		$p[username] = $a[username];
		$p[title] = $a[title];
		if(preg_match('#^http#', $a[coverimg]) != 1 && !empty($a[coverimg])){
			$a[coverimg] = 'http://roseimg.modtv.co.kr/playlist_cover/'.$a[coverimg];
		}else{
			$track=query("select snippet from track where playlistno=:no limit 1 offset 0", $a);
			$thumbnails = json_decode($track[0][snippet], true)[thumbnails];
			if(!empty($thumbnails['default'][url]))
				$a[coverimg] = $thumbnails['default'][url];		
			if(!empty($thumbnails[medium][url]))
				$a[coverimg] = $thumbnails[medium][url];
			if(!empty($thumbnails[high][url]))
				$a[coverimg] = $thumbnails[high][url];					
		}
		$p[coverimg] = $a[coverimg];
		$p[rank] = $a[rank];
		if($a[star])
			$p[star] = $a[star];
		$p[memo] = $a[memo];
		$p[type] = $a[type];
		$p[toshare] = $a[toshare];
		$p[isdefault] = $a[isdefault];
		$p[totalcount] = $a[totalcount];
		if($a[no]){
			$tag = new Tag();
			$p[tags] = $tag->getTagbyPlaylist($a[no]);
		}	
		$p[tracks] = $a[tracks];
		$p[updatetime] = $a[updatetime];
		$p[creationtime] = $a[creationtime];
		$result = $p;
		return $result;		
	}
	function get($no){		
		$r = query("select * from playlist where no=$no");
		if(isset($r[0]))
			$playlist = $this->makeDefaultPlaylist($r[0]);
		else
			$playlist = $r;
		return $playlist;
	}
	function get_fav_playlists($a){
		if(isset($a[range_start]) && isset($a[range_end]))
			$range = ' limit '.$a[range_end].' offset '.$a[range_start];
		
		$favList = query('
			select p.*, (select count(*) from track t where p.no = t.playlistno and t.snippet is not null) as totalcount 
			from playlist p join playlist_favorites f  
			on 
				f.playlist_no = p.no
			where 
				f.username =:username
		 '.$range, $a);
		 
		$totalcount = query('
			select count(p.no) as totalcount
			from playlist p join playlist_favorites f  
			on 
				f.playlist_no = p.no
			where 
				f.username =:username
		 ', $a);
		 
		$favArr[totalcount] = $totalcount[0][totalcount];
		foreach($favList as $playlist)
			$playlistArr[] = $this->makeDefaultPlaylist($playlist);
		$favArr["playlists"] = $playlistArr;
		return $favArr;
	}
	function get_star_playlists($a){
		if(!$a[star])
			$a[star] = 5;
		if(isset($a[range_start]) && isset($a[range_end]))
			$range = ' limit '.$a[range_end].' offset '.$a[range_start];

		$starList = query('
			select p.*, s.star, (select count(*) from track t where p.no = t.playlistno and t.snippet is not null) as totalcount
			from playlist p join playlist_star s  
			on 
				p.no = s.playlist_no 
			where 
				s.username =:username and
				s.star >=:star
		'.$range, $a);
		
		$totalcount = query('
			select count(p.no) as totalcount
			from playlist p join playlist_star s  
			on 
				p.no = s.playlist_no 
			where 
				s.username =:username and
				s.star >=:star', $a);
				
		$starArr[totalcount] = $totalcount[0][totalcount];	
		foreach($starList as $playlist){
			$playlistArr[] = $this->makeDefaultPlaylist($playlist);
		}	
		$starArr["playlists"] = $playlistArr;
		return $starArr;
	}	
}

/**
	playlist fetch
	username 으로 fetch ok 
	no 으로 fetch ok 
	
	1. 1개의 플레이리스트 정보 가져오기 
	type = list of roseplaylist  - track limit 1 
	type = roseplaylist - track limit 10
	
	2. 리스트 of 플레이리스트 정보 가져오기
	playlist coverimg 없을 시 첫번쨰 track의 thumbnails를 대신 가져옴 
	high -> medium -> default 이미지 품질 순으로 없으면 대안책으로 가져옴 
*/		
$app->action('playlist/fetch', function() use($auth){
	$playlist = new Playlist();
	$track = new Track();
	$a = $_REQUEST;
	$isstar = $a[isstar];
	// 플레이리스트의 star, favorite 만 가져옴 
	if($a[star_fav] && $a[no] && $a[username]){	
		$star = query('select star from playlist_star where username=:username and playlist_no=:no', $a);
		if(!empty($star))
			$result[star] = $star[0][star];
		else
			$result[star] = 0;
		
		$favorites = query('select * from playlist_favorites where username=:username and playlist_no=:no', $a);
		if(!empty($favorites))
			$result[favorites] = "1";		
		else
			$result[favorites] = "0";
		reply_json($result);
		return;
	}	
	
	if($isstar){
		$starlist = '"별점 '.$isstar.'점 플레이리스트"';
		for($i=$isstar+1; $i < 6 ; $i++)
			$starlist = $starlist.', "별점 '.$i.'점 플레이리스트"';
		$condition = $condition.'and p.title in ('.$starlist.') ';	
	}else{
		$condition = $condition.' and p.title not in ("별점 1점 플레이리스트", "별점 2점 플레이리스트", "별점 3점 플레이리스트", "별점 4점 플레이리스트","별점 5점 플레이리스트") ';
	}
	if($a[type])
		$condition = $condition.' and p.type=:type ';
	if(isset($a[range_start]) && isset($a[range_end]))
		$range = ' limit '.$a[range_end].' offset '.$a[range_start];
	if($a[title])
		$condition = $condition.' and p.title=:title ';
	if($a[toshare])
		$condition = $condition.' and p.toshare=:toshare ';

	if($a[isowner]==1 && isset($a[isowner]))
		$condition = $condition.' and p.toshare=1 ';
	
	if($a[isowner]==2 && isset($a[isowner]))
		$condition = $condition.' and p.toshare in (1,2)';	
	
	$playlists=query(
		"select p.*,(select count(*) from track t where p.no = t.playlistno and t.snippet is not null) as totalcount
		from playlist p 
		where 
			p.username=:username ".$condition.
		"order by rank asc".$range, $a);
		
	// $isstar 이상의 별점 플레이리스트 no return; 	
	if($isstar){
		foreach($playlists as $val){
			$no[] = $val[no];
		}
		$result[no] = implode (",", $no);;
		reply_json($result);
		return;
	}		
		
	// 트랙정보까지 포함하여 playlist 한개 가져오기 
	if($a[username] && $a[title]){
		if(!$playlists[0]){
			reply_json(response(404));
			return;
		}else{
			$a = $playlists[0];	
			if($a[isListofPlaylist]==1)
				$limitNum = 1;
			else
				$limitNum = 10;

			$tracks=query("select * from track where playlistno=:no limit ".$limitNum." offset 0", $a);		
			for($i=0;$i<count($tracks);$i++)
				$trakArr[] = $track->makeDefaultTrack($tracks[$i]);	
			
			$a[tracks] = $trakArr;
			$p = $playlist->makeDefaultPlaylist($a);
			reply_json($p);		
			return;
		}
	}
		
	for($i=0;$i<count($playlists);$i++){
		$playlists[$i][username] = $a[username];
		$playlistArr[] = $playlist->makeDefaultPlaylist($playlists[$i]);		
	}
	
	if($a[old_version] == 1){
		reply_json($playlistArr);	
		return;
	}

	$re = query("select count(*) as totalcount from playlist p where p.username=:username ".$condition, $a);	
	$list_of_playlists[totalcount] = $re[0][totalcount];
	
	//if(!isset($a[isstar])){
	$a[range_start]=0;
	$a[range_end]=4;
	$list_of_playlists[favoriteList] = $playlist->get_fav_playlists($a);
	//}	
	$list_of_playlists[playlists] = $playlistArr;
	reply_json($list_of_playlists);			
		
});

$app->action('playlist/updateproperty', function() use($auth){
	$playlist = new Playlist();
	$a = $_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){	
		// 태그 삭제랑 데이터 안보낸거 체크하기 
		if($a[tags]){
			$tag = new Tag();
			$tag->deleteTagInPlaylist($a);
			$tag->addTagToPlaylist($a);
		}
		if($_FILES["coverimg"]){
			$image = new Image();
			$result=$image->uploadFile("../../roseimg/playlist_cover/", $_FILES["coverimg"], "medium");
			if($result[success]==1){
				$a[coverimg] = $result[unique_name];
			}
		}
		if($a[title])
			$condition = " title=:title, ";
		if($a[memo])
			$condition = $condition." memo=:memo, ";	
		if($a[coverimg])
			$condition = $condition." coverimg=:coverimg, ";			
		$a = $playlist->makeDefaultPlaylist($a);
		
		$result = query("
		update playlist set".$condition." 
			rank=:rank,
			type=:type,
			toshare=:toshare,
			updatetime=now()
		where no=:no", $a);
		
		if($result[numAffected]==1){
			reply_json($playlist->get($a[no]));	
		}	
	}else{
		reply_json($authorized);
	}	
});


$app->action('playlist/new', function() use($auth){
	$playlist = new Playlist();
	$a = $_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){		
		if($_FILES["coverimg"]){
			$image = new Image();
			$result=$image->uploadFile("../../roseimg/playlist_cover/", $_FILES["coverimg"], "medium");
			if($result[success]==1){
				$a[coverimg] = $result[unique_name];
			}
		}
		if($a[username]){
			$r = query("select no from info where username =:username", $a);
			$a[user_no] = $r[0][no];
		}
		
		$a = $playlist->makeDefaultPlaylist($a);
		$result = query("
		insert into playlist set 
			username=:username,
			user_no=:user_no, 
			title=:title,
			coverimg=:coverimg, 
			rank=:rank,
			memo=:memo, 
			type=:type,
			toshare=:toshare,
			isdefault=:isdefault
		", $a);
		if($result[numAffected]==1){
			$a[no] = $result[lastInsertId];
			$tag = new Tag();
			$tag->addTagToPlaylist($a);
			reply_json($playlist->get($a[no]));	
		}
	}else{
		reply_json($authorized);
	}		
});

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

$app->action('playlist/uploadimg',function() use($auth){
	$image = new Image();
	$image->uploadFile("../../roseimg/playlist_cover/", $_FILES["coverimg"], "medium");
});

$app->action('playlist/download',function() use($auth){
	$playlist = new Playlist();
	$track = new Track();
	$a=$_REQUEST;
   	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){		
		if($a[isdebug]!=1){
			header('Content-disposition: attachment; filename=playlist_'.$a[title].'.json');
			header('Content-type: application/json');		
		}
		if($a[username] && $a[title]){
			$info = query('select * from info where username=:username', $a);
			if(!$info[0]){
				'username이 존재하지 않습니다.';
				return;
			}else{
				if(!$playlist[0]){
					'플레이리스트가 존재하지 않습니다.';
					return;
				}else{
					$info = query('select * from info where username=:username', $a);
					$a[user_no] = $info[0][no];					
					$p= query('select * from playlist where title=:title and username=:username', $a);
					$tracks=query("select * from track where playlistno=".$p[0][no]);
					for($i=0;$i<count($tracks);$i++)
						$trakArr[] = $track->makeDefaultTrack($tracks[$i]);										
					$p[tracks] = $trackArr ;
					echo json_encode($playlist->makeDefaultPlaylist($p),JSON_UNESCAPED_UNICODE);					
				}	
			}
		}else{
			echo 'username, 플레이리스트명 필수';
		}
	}else{
		reply_json($authorized);
	}			
});
/*
	playlist tag
	1. add
	2. delete
*/
$app->action('playlist/addtag',function() use($auth){
	$tag = new Tag();
	$tag->addTagToPlaylist($_REQUEST); 
});
$app->action('playlist/deletetag',function() use($auth){
	$tag = new Tag();
	$tag->deleteTagInPlaylist($_REQUEST);
});

/*
	playlist favortie 
	1. add
	2. delete
	3. get 
*/
$app->action('playlist/favorites/add', function() use($auth){
	$playlist = new Playlist();
	$a = $_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){		
		$r = query('insert into playlist_favorites set username=:username, playlist_no=:playlistno, rank=0', $a);	
		if($r[numAffected]==1){
			$result[result] = 'success';
			reply_json($result);	
		}	
	}else{
		reply_json($authorized);
	}		
});

$app->action('playlist/favorites/delete', function() use($auth){
	$playlist = new Playlist();
	$a = $_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){		
		$r = query('delete from playlist_favorites where username=:username and playlist_no=:playlistno', $a);	
		if($r[numAffected]==1){	
			$result['result'] = 'success';
			reply_json($result);	
		}else{
			reply_json(response(404));
		}
	}else{
		reply_json($authorized);
	}		
});

$app->action('playlist/favorites/get', function() use($auth){
	$playlist = new Playlist();
	$a = $_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){		
		$r = $playlist->get_fav_playlists($a);
		reply_json($r);		
	}else{
		reply_json($authorized);
	}		
});

/**
	playlist star 
	- add 
	- delete 
	- get 
*/

$app->action('playlist/star/modify', function() use($auth){
	$playlist = new Playlist();
	$a = $_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){		
		$star = query('select * from playlist_star where username=:username and playlist_no=:playlistno', $a);
		if(empty($star)){
			$r = query('insert into playlist_star set username=:username, playlist_no=:playlistno, rank=0, star=:star', $a);	
		}else{
			$r = query('update playlist_star set star=:star where username=:username and playlist_no=:playlistno', $a);
		}
		if($r[numAffected]==1){	
			$result[result] = 'success';
			reply_json($result);	
		}
	}else{
		reply_json($authorized);
	}		
});

$app->action('playlist/star/delete', function() use($auth){
	$playlist = new Playlist();
	$a = $_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){		
		$r = query('delete from playlist_star where username=:username and playlist_no=:playlistno', $a);	
		if($r[numAffected]==1){	
			$result['result'] = 'success';
			reply_json($result);
		}else{
			reply_json(response(404));
		}
	}else{
		reply_json($authorized);
	}		
});

$app->action('playlist/star/get', function() use($auth){
	$playlist = new Playlist();
	$a = $_REQUEST;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){		
		$r = $playlist->get_star_playlists($a);
		reply_json($r);		
	}else{
		reply_json($authorized);
	}		
});

/**
	playlist newset
	기본 플레이리스트 자동생성
*/
$app->action('playlist/newset', function() use($auth){
	$playlist = new Playlist();
	$a = $_REQUEST;
	$authorized = $auth->verify($a[accesskey]);
	if($authorized['status'] == 'OK'){
		
		$url = 'http://roseapi.modtv.co.kr';
		$url .= '/playlist/new';

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

		for($i=1;$i<6;$i++)
		{
			$params = array(
				'username' => $a[username],
				'title' => '별점 '.$i.'점 플레이리스트',
				'isdefault' => 1,
				'accesskey' => $a[accesskey]
			);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
			curl_exec($ch);
		}

		$params = array(
			'username' => $a[username],
			'title' => '즐겨찾기 플레이리스트',
			'isdefault' => 1,
			'accesskey' => $a[accesskey]
		);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
		curl_exec($ch);
		
		$params = array(
			'username' => $a[username],
			'title' => '기본 플레이리스트',
			'isdefault' => 1,
			'accesskey' => $a[accesskey]
		);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
		curl_exec($ch);
		
		curl_close($ch);
		$result[result] = 'success';
		$result[msg] = 'playlist setting success';
		reply_json($result);
	}else{
		reply_json($authorized);
	}
});

/**
	playlist crud -> 거의안씀 
*/
$app->action('playlist/crud', function() use($auth){
	$playlist = new Playlist();
	$a = $_REQUEST;
	$cmd = $_SERVER[REQUEST_METHOD];	
	if($a[username]){
		$r = query("select no from info where username =:username", $a);
		$a[user_no] = $r[0][no];
	}	
	switch($cmd)
	{
	case 'POST':
		$params = build_mysql_params(array(
			title, user_no, rank, memo, coverimg, type, username
		), $a);
		$result = query("insert into playlist set $params");
		reply_json($playlist->get($result[lastInsertId]));			
		break;
	case 'PUT':
		$a = file_get_contents('php://input');
		$a = json_decode($a, true);	
		$params = build_mysql_params(array(
			title, user_no, rank, memo, coverimg, type, username
		), $a);
		query("update playlist set $params where no=".$a[no]);
		reply_json($playlist->get($a[no]));	
		break;
	case 'GET':
		reply_json($playlist->get($a[no]));		
		break;
	case 'DELETE':
		$no = get_url_no();
		query("delete from playlist where no=$no");
		echo "[]";
		break;
	}
});	

?>