<?php
require '../../fly2/fly3.php';
//require 'config.php';
include_once('stack.php');

class RML {	
	public $rml_upload_path = 'uploads/';
	public $parse_result_path = 'parse_result/';	
	
	function countFrontTab($line)
	{
		$result = 0;
		for($i = 0; $i < strlen($line); $i++) {
			$c = $line[$i];
			//echo "$c";
			if ($c == " ")
				$result++;
			else
				break;
		}
		return $result;
	}
	
	function __parse(&$lines, &$cur, $tab)
	{
		$newtab == -2;
		$lasttitletab = -1;
		$lineno = 1;
		while(count($lines) > 0) { 
			$lineno++;
			$line = $lines[0];
			//array_splice($lines, 0, 1);
			$n = $this->countFrontTab($line);
			//echo "$line $newtab $tab\n";
			
			if ($n <= $tab)  //재귀종료
				return;
			if ($newtab == -2)
				$newtab = $n;
			//if ($n > $newtab)
				//return;
			
			//$re = '/\*([-\w\d\s가-힣]*)\n/';
			$re = '/\*(.*)/';
			preg_match_all($re, $line, $matches);
			//print_r($matches);
			if (count($matches[1]) == 1) { // 블럭 타이틀일때 재귀
				if(strpos($matches[1][0], "/") !== false)
					throw new Exception("메뉴명에는 /(슬러시)가 포함될 수 없습니다. $line(line: $lineno)");
				$key = trim($matches[1][0]);				
				if ($n == $newtab) {
					$newnode = array(
						nm=>$key
					);
					array_splice($lines, 0, 1);
					$this->__parse($lines, $newnode, $n);
					array_push($cur, $newnode); 
				} else
				if ($n > $newtab) {
					//echo "last title tab $lasttitletab $n\n";
					if ($lasttitletab != -1)
						if ($n != $lasttitletab)
							throw new Exception("부모없는 자식 $line(line: $lineno)");
					$lasttitletab = $n;
					
					if (!isset($cur[submenu]))
						$cur[submenu] = array();
					$newnode = array(
						nm=>$key
					);
					array_splice($lines, 0, 1);
					$this->__parse($lines, $newnode, $n);
					array_push($cur[submenu], $newnode);
				} else {
					throw new Exception("parse error");
				}
				//array_push($cur[$key], $result);
				continue;
			}			
			$re = "/\[(.*)=(.*)\]/";
			preg_match_all($re, $line, $matches);
			//print_r($matches);
			if (count($matches[1]) == 1) { // 속성
				//print_r($matches[1][0]);
				if($matches[1][0] == 'main_artist')
					$cur[image] = $this->getArtistimg($matches[2][0])[picture];
				$cur[$matches[1][0]] = $matches[2][0];
				array_splice($lines, 0, 1);
				continue;
			}
			//$re = "/\s=(.*)/";
			$re = "/\s=(.*\S)/";
			preg_match_all($re, $line, $matches);
			//print_r($matches);
			if (count($matches[1]) == 1) { // URL
				if (!isset($newnode[url]) && !isset($cur[_URLs]))
					$cur[_URLs] = array();
				array_push($cur[_URLs], $this->combinate_info($matches[1][0], $cur[type]));
				array_splice($lines, 0, 1);
				continue;
			}			
			if (trim($line) == "") {//공백라인
				array_splice($lines, 0, 1);
				continue;
			}				
			throw new Exception("Syntax Error - $line(line: $lineno)");
		}
	}
	
	function parse($src)
	{
		$lines = explode("\n", $src);
		
		foreach($lines as &$line) {
			$line = "    ".$line;
		}
		array_unshift($lines, "* root");
		$currenttab = -1;
		$all = array(
			//submenu=>array(),
		);
		$this->__parse($lines, $all, -1);
		
		//print_r($all);
		// array -> object 로 돌려주세요. (7/11 이원석과장 요청)
		return $all[0];
	}
	function upload_rml($rml){
		if(0 < $rml['error'])
			echo 'Error: ' . $rml['error'] . '<br>';
		else
			move_uploaded_file($rml['tmp_name'], $this->rml_upload_path.$rml['name']);
		return file_get_contents($this->rml_upload_path.$rml['name']);
	}
	
	function upload_parse_result($name, $all){
		file_put_contents($this->parse_result_path.$name.'.json', json_encode($all,JSON_UNESCAPED_UNICODE)); 	
	}
	/**
		url 이 플레이리스트인 경우 
		플레이리스트의 기본 정보 -> 제목, 커버이미지, tocaltrack 수, 트랙 최대 10개까지만 불러옴	
		url youtube(track)이면 바로 youtube api 호출 
		전체 정보 불러오면 됨 	
	*/
	function combinate_info($url, $type){
		preg_match_all('/([^?&=#]+)=([^&#]*)/',$url,$match);
		if(strpos($url, 'youtube.com')){ 
			if(!in_array("v", $match[1]))
				throw new Exception('Syntax Error - not set parameter [v]'."\n".$url);		
		}else{
			if(!in_array("title", $match[1]))
				throw new Exception('Syntax Error - not set parameter [title]'."\n".$url);
			if(!in_array("username", $match[1]))
				throw new Exception('Syntax Error - not set parameter [username]'."\n".$url);	
			$url = explode('?', $url)[0];
			if($type=='RosePlayList')
				$url = $url.'?title='.urlencode($match[2][0]).'&username='.urlencode($match[2][1]).'&isListofPlaylist=0';	
			if($type=='list of RosePlayList')
				$url = $url.'?title='.urlencode($match[2][0]).'&username='.urlencode($match[2][1]).'&isListofPlaylist=1';	
			if($type=='YoutubePlayList')
				$url = $url.'?playlistid='.urlencode($match[2][0]).'&title='.urlencode($match[2][1]).'&usrename='.($match[2][2]);
		}
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$res = curl_exec($ch);
		curl_close($ch);
		return json_decode($res, true);
	}
	
	function get_menu($menu_name, $lang = 'ko'){
		if($lang != 'ko')
			$menu_name = $menu_name.'_'.$lang; 
		echo file_get_contents($this->parse_result_path.$menu_name.'.json');	
	}	
	/*
		$name = 장르별
		$name = 장르별/팝
		$name = 장르별/팝/팝 For you
		$name = 상황별/휴식 
		$name = 상황별/드라이브 
		$name = 힙합 For you 
		$name = Rose 추천리스트 
		
		1. 속성과 array 거르기 
		2. path 기준은 "/" 
	*/
	function get_submenu($arr, $path){
		if(!$path){
			$arr[hideURLs]=true;	
			return $arr;
		}
		$path = explode("/", $path);
		for($i=0;$i<count($path);$i++){
			if(isset($arr[submenu])){
				foreach($arr[submenu] as $submenu){
					//$submenu[hideURLs]=false;	
					if(isset($submenu[nm]) && trim($submenu[nm]) == trim($path[$i])){
						$arr = $submenu;
						//if($submenu[type]=='keyword' || $arr[type]=='menu')
							//$submenu[hideURLs]=true;								
						if($i==count($path)-1)
							return $submenu;		
					}
				}
			}
		}
	}
	function type확인해서거르기(&$array){
		foreach($array[submenu] as &$submenu){
			if($submenu[type] != 'keyword')
				$submenu[hide_URLs] = "false";	
		}
		return $array;		
	}
	function findandRemove(&$array, $target ){
		foreach($array as $key => &$value){ 
			if(array_key_exists('hide_URLs', $array) == false){
				if(is_array($value)){
					if($key == $target)
						unset($array[_URLs]);
					$this->findandRemove($value, $target);
				}
			}else{
				//echo $key."  :  ".$value."\n";
			}			
		}
		return $array;
	}
	function getArtistimg($artist){
		$postdata = array(
			"name"=>$artist
		);		
		$url = 'http://rose.modtv.co.kr/api/search/artist';
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postdata));		
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$res = curl_exec($ch);
		curl_close($ch);
		return json_decode($res, true);	
		
	}
}
$app->action('parse', function (&$view) {
	//print_r($_REQUEST);
	$a = $_REQUEST;
	$src = $a[src];
	$app = new RML();
	$all = $app->parse($src);
	if($a[name]){
		file_put_contents($app->rml_upload_path.$a[name].'.txt', $a[src]);
		file_put_contents($app->parse_result_path.$a[name].'.json', json_encode($all,JSON_UNESCAPED_UNICODE)); 
		if($a[lang])
			$app->get_menu($a[name], $a[lang]);
		else
			$app->get_menu($a[name]);
	}else{
		reply_json($all);
	}
});

$app->action('index', function (&$view) {
	$view = 'index';	
});

$app->action('menu/get', function(){
	$app = new RML();
	$a = $_REQUEST;
	if($a[lang] && $a[lang] != 'ko')
		$name = $a[name].'_'.$a[lang];
	else
		$name = $a[name];

	$arr = json_decode(file_get_contents($app->parse_result_path.$name.'.json'), true);
	
	$submenu = $app->get_submenu($arr, $a[submenu]);
	$submenu = $app->type확인해서거르기($submenu);
	$submenu = $app->findandRemove($submenu,'_URLs');
	reply_json($submenu);
});

?>
