<?php

header("Access-Control-Allow-Origin: *");

/**
image title 모음
*/
require '../../fly2/fly3.php';
require 'config.php';

include_once 'rose_utils.php';
include_once 'search.php';
include_once 'loot/img.php';
include_once 'loot/melon.php';

class RoseApi {
	function fetchGenre($a) {
		$q = "select * from genre limit 100";
		$rows = query($q, $a);
		return $rows;
	}
	function fetchAlbum($a) {
		$q = "select * from album limit 100";
		$rows = query($q, $a);
		return $rows;
	}
	function searchGenreAlias($g) {
		if (!$g)
			return "%%";
		$rows = query("select * from genre_alias where `alias` like '%$g%'");
		if (count($rows) == 0)
			return "$g";
		return $rows[0][realname];
	}
	function search($a) {
		$a[genre] = $this->searchGenreAlias($a[genre]);
		//$a[otitle] = $a[title];
		if ($a[title])
			$qtitle = " and match(title) against(:title) ";
		if ($a[deep]) {
			$a[genre] = "%$a[genre]%";
			$a[title] = "%$a[title]%";
			$qtitle = " and title like :title ";
			$a[artist] = "%$a[artist]%";
			$a[year] = "%$a[year]%";
		} else {
			$a[genre] = "$a[genre]%";
			//$a[title] = "$a[title]%";
			$a[artist] = "$a[artist]%";
			$a[year] = "%$a[year]";
		}
		$q = "
			select * from album 
			where
				true 
				$qtitle
				and genre like :genre
				and artist like :artist
				and year like :year
			limit 100				
		";
		$rows = query($q, $a);
		
		foreach($rows as &$row) {
			//echo $row[artist];
			preg_match('/[가-힣]+/', $row[artist], $matches);
			if ($matches) {
				$row[artist] = $matches[0];
			}
			
		}
		return $rows;
	}
	
	function searchTracks($a) {
		//$a[genre] = $this->searchGenreAlias($a[genre]);
		//$a[deep] = true;
		$qtitle = " and match(a.title) against(:title) ";
		$otitle = $a[title];
		if ($a[deep]) {
			//$a[genre] = "%$a[genre]%";
			$a[title] = "%$a[title]%";
			//$a[artist] = "%$a[artist]%";
			//$a[year] = "%$a[year]%";
		} else {
			//$a[genre] = "$a[genre]%";
			$a[title] = "$a[title]%";
			//$a[artist] = "$a[artist]%";
			//$a[year] = "%$a[year]";
		}
		if (strlen($otitle) < 7)
			$qtitle = " and a.title like '$a[title]' ";
		
		$q = "
			select a.*, b.title as album_title, b.artist as album_artist from track a 
				left join album b on a.albumno=b.no
			where
				true
				-- and a.title like :title and like :title
				
				-- and a.title like '%돌아와요'
				$qtitle
			limit 100
		";
		//echo $q;
		$rows = query($q, $a);
		return $rows;
	}
	
	
}

$app->action('api/genre/fetch', function () {
	$app = new RoseApi();
	$rows = $app->fetchGenre($_REQUEST);
	reply_json($rows);	
});

$app->action('api/track/fetch', function () {
});

$app->action('api/album/fetch', function () {
	$app = new RoseApi();
	$rows = $app->fetchAlbum($a);
	reply_json($rows);
});

$app->action('api/search', function(){
	$app = new RoseApi();
	$rows = $app->search($_REQUEST);
	$a = $_REQUEST;
	setcookie8("artist", $a[artist]);
	setcookie8("title", $a[title]);
	setcookie8("genre", $a[genre]);
	setcookie8("year", $a[year]);
	reply_json($rows);
});

$app->action('api/track/search', function(){
	$app = new RoseApi();
	$rows = $app->searchTracks($_REQUEST);
	$a = $_REQUEST;
	setcookie8("artist", $a[artist]);
	setcookie8("track_title", $a[title]);
	setcookie8("genre", $a[genre]);
	setcookie8("year", $a[year]);
	reply_json($rows);
});


$app->action('index', function (&$view) {
	$view = 'index';	
	//return array(all=>$all, hospital=>$app->getHospital());
});


$app->action('albums', function (&$view) {
	$view = 'index';	
	//return array(all=>$all, hospital=>$app->getHospital());
});

$app->action('tracks', function (&$view) {
	$view = 'tracks';	
	//return array(all=>$all, hospital=>$app->getHospital());
});

/*
function get1stGoogleImage($search_keyword)
{
	include_once('simple_html_dom.php');
	//$search_keyword= $a[q];//$_GET['name'];
	$search_keyword=str_replace(' ','+',$search_keyword);
	//$newhtml = file_get_html("https://www.google.com/search?q=".$search_keyword."&tbm=isch&gws_rd=cr&ei=16E0WMGSKYmisAHmp6b4Ag");
	//$newhtml = file_get_html("https://www.google.com/search?q=".$search_keyword."&tbm=isch");
	//file_put_contents("search.txt", $newhtml);
	$options = array(
	  'http'=>array(
		'method'=>"GET",
		'header'=>"Accept-language: en\r\n" .
				  "Cookie: foo=bar\r\n" .  // check function.stream-context-create on php.net
				  "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" // i.e. An iPad 
	  )
	);

	$context = stream_context_create($options);
	$url = "https://www.google.co.kr/search?hl=en&tbm=isch&source=hp&q=".$search_keyword;
	$html = file_get_contents($url, false, $context);
	echo $html;
	$newhtml = str_get_html($html);
	$result_image_source = $newhtml->find('.images_table', 0)->find('img', 0)->src;
	return $result_image_source;
}

*/

$app->action('util/imgurl', function(){
	//return;
	$a = $_REQUEST;
	$url = get1stGoogleImage($a[q]);
	reply_json(
		array(
			url=>$url,
			hresult=>0,
		)
	);
});

$app->action('util/img', function(){
	$a = $_REQUEST;
	$url = get1stGoogleImage($a[q]);
	$img = file_get_contents($url);
	header("Content-type: image/jpeg");
	header('Content-Length: ' . count($img));
	echo $img;
});

$app->action('album', function(&$view){
	$a = $_REQUEST;
	$rows = query("select * from album where no=$a[discno]");
	//print_r($rows);
	$album = $rows[0];
	$rows = query("select * from track where albumno=$album[no]");
	foreach($rows as &$row)
	{
		if (!$row[artist])
			$row[artist] = $album[artist];
	}
	//print_r($rows);
	$view = 'album.pug';
	$albums = "";
	
	$loot = new ImageLoot();
	$images = json_decode($loot->urlsByTitle(array(
			q=>"$album[title] - $album[artist]"
		)));
	//print_r($images);
	$images = array_slice($images, 0, 20);
	return array(
		tracks=>$rows,
		album=>$album,
		images=>$images,
	);
});

$app->action('artist', function(&$view) {
	$view = 'artist';
	return array(
		params=>$_REQUEST,
	);
});

$app->action('api/v3/artist', function(&$view){
	$a = $_REQUEST;
	
	$rows = query("select * from q_artist where q=:q", $a);
	//$rows=null;
	if(!count($rows)) {
		$loot = new MelonLoot();
		$loot->stealArtist($a[q]);
		$rows = query("select * from q_artist where q=:q", $a);
	}
	$artistno = $rows[0][artistno];
	
	$rows = query("select * from artist_melon where no=$artistno");
	$result = $rows[0];
	unset($result[melonid]);

	$loot = new ImageLoot();
	$images = json_decode($loot->urlsByTitle(array(
			q=>"가수 $result[name] $result[county]"
		)));
	//print_r($images);
	$result[image] = $images[0];
	$images = array_slice($images, 1, 20);
	$result[images] = $images;

	reply_json($result);
});

$app->action('api/image/fetch', function(&$view){
	$a = $_REQUEST;


	$loot = new ImageLoot();
	if(!$a[q])
		die("no query string");

	$rd = new RoseMusicDb();
	//$a[name] = 'Michael Jackson';
	
	switch (strtolower($a[category])) {
	case 'artist':
		$qa = array(
			name=>$a[q],
		);
		$artist = $rd->searchArtistDB($qa);	
		if (!$artist || $artist[bio] == '' || $a[forceupdate]) {
			$rd->stealArtistFromTidal($a);
			$artist = $rd->searchArtistDB($a);
			if(!$artist)
				die("can't find artist $a[q]");
		}
		$imgqs = "artist $artist[name] $artist[county]";
		break;
	case 'album':
		$qa = array(
			title=>$a[q],
			artist=>$a[artist],
		);
		$album = $rd->searchAlbumDb($qa);		
		if (!$album || $album[tidalid] == '' || $a[forceupdate]) {
			$rd->stealAlbumFromTidal($qa);
			$album = $rd->searchAlbumDb($qa);
			if(!$album)
				die("can't find album $a[q]");
		}
		$imgqs = "album $album[title] $album[artist]";
		break;
	default:
		die("invalid category $a[category]");
		break;
	}
	
	$images = json_decode($loot->urlsByTitle(array(
			q=>$imgqs
	)));
	//print_r($images);
	foreach($images as &$img) {
		$img = "http://images.weserv.nl/?".http_build_query(array(url=>$img));
	}
	$result[image] = $images[0];
	$images = array_slice($images, 1, 20);
	$result[images] = $images;
	$result[artist] = $artist;
	$result[album] = $album;
	if ($a[ashtml])
	{
		$GLOBALS[app]->layout = 'layout_api';
		$view="fetchImage";
		return $result;
	} else		
		reply_json($result);
});

?>