<?php
class Subscribe{
	function get($a){
		if($a[username])
			$user_no = query('select no from info where username=:username', $a);
		if(!empty($user_no)){
			$a[user_no] = $user_no[0][no];	
			$condition = $condition.' and user_no=:user_no ';
		}
		if($a[no])
			$condition = $condition.' and no=:no';
		if($a[channel_id])
			$condition = $condition.' and channel_id=:channel_id';
		
		$infos = query('select * from subscribe where 1 '.$condition, $a);
		
		for($i=0;$i<count($infos);$i++){
			if(empty($infos[$i][thumbnails])){
				$youtubev3 = new YoutubeV3();
				$a = $youtubev3->getChannel($infos[$i][channel_id]);
				if($a[result] == 'success'){
					$a[title]= json_encode($a[title], JSON_UNESCAPED_UNICODE);
					$a[thumbnails]= json_encode($a[thumbnails], JSON_UNESCAPED_UNICODE);
					$a[channel_id] = $infos[$i][channel_id];
					// 제목, 설명, 트랙의 썸네일, 상세설명, 동영상분석정보 DB에 넣기 
					$result = query("
						update subscribe set
							title=:title,
							thumbnails=:thumbnails
						where channel_id=:channel_id", $a);		
				}		
			}
			$infos[$i][thumbnails] = json_decode($infos[$i][thumbnails]);
			$infos[$i][title] = json_decode($infos[$i][title]);			
		}		
		return $infos;
	}	
}

$app->action('user/subscribe/get', function () use($info, $auth){
	$a=$_REQUEST;
	$subscribe = new Subscribe;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){
		reply_json($subscribe->get($_REQUEST));
	}else{
		reply_json($authorized);
	}	
});

$app->action('user/subscribe/new', function () use($info, $auth){
	$a = $_REQUEST;
	$subscribe = new Subscribe;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){
		$user_no = query('select no from info where username=:username', $a);
		if($user_no)
			$a[user_no] = $user_no[0][no];
		$result = query('insert into subscribe set user_no=:user_no, channel_id=:channel_id', $a);
		if($result[numAffected]==1){
			$a[no] = $result[lastInsertId];
			reply_json($subscribe->get($a));
		}
	}else{
		reply_json($authorized);
	}	
});

$app->action('user/subscribe/cancel', function () use($info, $auth){
	$a = $_REQUEST;
	$subscribe = new Subscribe;
	$authorized = $auth->verify($a[accesskey]);	
	if($authorized['status'] == 'OK'){
		$user_no = query('select no from info where username=:username', $a);
		if($user_no)
			$a[user_no] = $user_no[0][no];
		$result = query('delete from subscribe where user_no=:user_no and channel_id=:channel_id', $a);
		if($result[numAffected]==1){
			echo '[]';
		}else{
			reply_json(response(404));
		}	
	}else{
		reply_json($authorized);
	}	
});
?>