<?php

include_once '../../fly2/fly3.php';
include_once 'config.php';
include_once 'rose_utils.php';
include_once "thiefs.php";


class TidalApi {
	function _callTidal($path, $params=null) {
		$curl = curl_init();
		if(!$params)
			$params = null;
		$params[countryCode] = 'US';
		
		$url = "http://api.tidal.com/v1/$path/?".http_build_query($params);
		//echo $url."\n";
		curl_setopt_array($curl, array(
		  CURLOPT_URL => $url,
		  CURLOPT_RETURNTRANSFER => true,
		  CURLOPT_ENCODING => "",
		  CURLOPT_MAXREDIRS => 10,
		  CURLOPT_TIMEOUT => 0,
		  CURLOPT_FOLLOWLOCATION => false,
		  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		  CURLOPT_CUSTOMREQUEST => "GET",
		  CURLOPT_HTTPHEADER => array(
			"X-Tidal-Token: kgsOOmYk3zShYrNP"
		  ),
		));
		$response = curl_exec($curl);
		$err = curl_error($curl);

		curl_close($curl);
		
		if ($err) 
			throw new Exception("cURL Error #:" . $err);
		return json_decode($response, true);
	}
	function _search($q, $type) {
		$params = array(
			query=>$q,
			types=>$type,
		);
		return $this->_callTidal('search', $params);		
	}
	function searchArtist($a) {
		$all = $this->_search($a[name], 'ARTISTS');
		//print_r($all);
		$artist = $all[topHit][value];
		//print_r($this->_callTidal("artists/$artist[id]"));
		$bio = $this->_callTidal("artists/$artist[id]/bio");
		
		return array(
			artist=>$artist,
			bio=>$bio,
		);
	}
	function searchAlbum($a) {
		$all = $this->_search("$a[title] $a[artist]", 'ALBUMS');
		$r = $all[topHit][value];
		//print_r($this->_callTidal("artists/$artist[id]"));
		$review = $this->_callTidal("albums/$r[id]/review");

		return array(
			album=>$r,
			review=>$review,
		);
	}
}
/**
	1. db에서 name 검색후 리턴
	2. 없을경우 tidal 검색
	3. tidal에서 발견된 artist는 db에 저장
*/

class RoseMusicDb {
	function getArtist($no)
	{
		$rows = query("select * from roseloot.artist where no=$no");
		return $rows[0];
	}
	function getAlbum($no)
	{
		$rows = query("select * from roseloot.album where no=$no");
		return $rows[0];
	}
	function _findAlbum($a)
	{
		$rows = query("select * from roseloot.album where title=:title and artist=:artist", $a);
		return $rows[0];
	}
	function _findArtist($a) {
		$rows = query("select * from roseloot.artist where name=:name", $a);
		return $rows[0];
	}
	function searchAlbumDb($a) {
		$rows = query("select * from roseloot.album_search where title=:title and artist=:artist", $a);
		//$rows = query("select * from album where title=:title", array(title=>$title));
		if(count($rows) == 0)
			return null;
		$r = $this->getAlbum($rows[0][albumno]);
		return $r;
	}
	function searchArtistDb($a) {
		$rows = query("select * from roseloot.artist where name=:name", $a);
		if (count($rows) > 0)
			return $rows[0];
		
		$rows = query("select * from roseloot.artist_search where name=:name", $a);
		//$rows = query("select * from album where title=:title", array(title=>$title));
		if(count($rows) == 0) {
			return null;
		}
		$r = $this->getArtist($rows[0][artistno]);
		//print_r($r);
		return $r;
	}
	function stealArtistFromTidal($a){
		$ta = new TidalApi();
		$t = $ta->searchArtist($a);
		$r = $t[artist];
		if(!$r[id])
			return;
		$r[tidalid] = $r[id];
		$r[bio] = $t[bio][text];
		if ($r[picture])
			$pic = "https://resources.tidal.com/images/".str_replace("-", "/", $t[artist][picture])."/750x750.jpg";
		$r[picture] = $pic;
		// alias 처리
		query("insert into roseloot.artist (name, tidalid, popularity, bio, picture)
			values
				(:name, :tidalid, :popularity, :bio, :picture)
			on duplicate key update 
				name=:name, tidalid=:tidalid, popularity=:popularity, bio=:bio, picture=:picture
		", $r);
		
		$t = $this->_findArtist($r);
		$a[artistno] = $t[no];
		query("insert into roseloot.artist_search
				(name, artistno)
			values
				(:name, :artistno)
			on duplicate key update 
				name=:name, artistno=:artistno", $a);
	}
	function stealAlbumFromTidal($a){
		$ta = new TidalApi();
		$t = $ta->searchAlbum($a); //.' '.$a[artist]);
		$pic = null;
		$r = $t[album];
		if(!$r[id])
			return;
		$r[tidalid] = $r[id];
		$r[review] = $t[review][text];
		if ($r[cover])
			$pic = "https://resources.tidal.com/images/".str_replace("-", "/", $r[cover])."/750x750.jpg";
		$r[cover] = $pic;
		$r[artist] = $r[artists][0][name];
		$result = query("insert into roseloot.album 
				(title, tidalid, popularity, review, cover, releasedate, artist)
			values
				(:title, :tidalid, :popularity, :review, :cover, :releaseDate, :artist)
			on duplicate key update 
				tidalid=:tidalid, popularity=:popularity, review=:review, cover=:cover, releasedate=:releaseDate
		", $r);
		// alias 처리
		$t = $this->_findAlbum($r);
		$a[albumno] = $t[no];
		query("insert into roseloot.album_search
				(title, artist, albumno)
			values
				(:title, :artist, :albumno)
			on duplicate key update 
				albumno=:albumno", $a);
	}
}

$app->action('api/search/artist', function () {
	$a = $_REQUEST;
		
	$rd = new RoseMusicDb();
	//$a[name] = 'Michael Jackson';
	$artist = $rd->searchArtistDB($a);	
	if (!$artist || $artist[bio] == '' || $a[forceupdate]) {
		$rd->stealArtistFromTidal($a);
		$artist = $rd->searchArtistDB($a);
	}
	
	if (!$artist[bio] || $a[forceupdate]) {
		if (!$artist[name]) {
			$artist[name] = $a[name];
		}
		$t = new DuckduckgoThief();
		$t = $t->stealArtist($artist[name]);
		//print_r($t);
		$artist[bio] = $t[bio];
		$artist[biofrom] = $t[url];
		//$artist[picture
		if ($artist[bio]){
			if ($artist[no]) {
				query("update roseloot.artist set bio=:bio, biofrom=:biofrom where no=:no", $artist);
			} else {
				query("insert roseloot.artist set name=:name, bio=:bio, tidalid=0, biofrom=:biofrom", $artist);
			}
		}
	}
	
	if (!$artist) {
		die("artist [$a[name]] not found");
	}
	
	reply_json($artist);
});

$app->action('api/search/album', function () {
	$a = $_REQUEST;
	if (!$a[title] || !$a[artist]) {
		die("title ans artist are needed");
	}
	$rd = new RoseMusicDb();
	$album = $rd->searchAlbumDb($a);
	
	if (!$album || $album[tidalid] == '' || $a[forceupdate]) {
		$rd->stealAlbumFromTidal($a);
		$album = $rd->searchAlbumDb($a);
		error_log("db updated .".json_encode($a));
	}
	//$
	if (!$album) {
		die("album [$a[title], $a[artist]] not found");
	}
	reply_json($album);
});

?>