﻿pl = {
	name: 'dplugin_Musixmatch',
	label: prop.Panel.Lang == 'ja' ? '歌詞検索: Musixmatch' : 'Download Lyrics: Musixmatch',
	author: 'Junya Renno',
	onStartUp: function () { // 最初に一度だけ呼び出される関数
	},
	onCommand: function (isAutoSearch) { // プラグインのメニューをクリックすると呼び出される関数
		if (!isAutoSearch && utils.IsKeyPressed(VK_CONTROL)) {
			plugins['splugin_AutoSearch'].setAutoSearchPluginName(this.name);
			return;
		}
		
		if (!fb.IsPlaying) {
			StatusBar.showText(prop.Panel.Lang == 'ja' ? '再生していません。' : 'Not Playing');
			return;
		}
		
		var debug_html = false; // for debug
		var depth = 0;
		var label = this.label.replace(/^.+?: /, '');
//		var NotAlphaNumericRE = /[^a-z0-9]/g;

		// title, artist for search
		var title = fb.TitleFormat('%title%').Eval();
		var artist = fb.TitleFormat('%artist%').Eval();

		if (!isAutoSearch) {
			title = prompt('Please input TITLE', label, title);
			if (!title) return;
			artist = prompt('Please input ARTIST', label, artist);
			if (!artist) return;
		}
		
		StatusBar.showText((prop.Panel.Lang == 'ja' ? '検索中......' : 'Searching......') + label);
		getHTML(null, 'GET', createQuery(artist,title), ASYNC, depth, onLoaded);

		//------------------------------------

		function createQuery(artist,title) {
			var UrlRE = /[\s|'|\/|\.|\,]+/g;
			artist = artist.replace(UrlRE,"-");
			artist = encodeURIComponent(artist).replaceEach("'", '%27', '\\(', '%28', '\\)', '%29', '%20', '+', 'g');
			title = title.replace(UrlRE,"-");
			title = encodeURIComponent(title).replaceEach("'", '%27', '\\(', '%28', '\\)', '%29', '%20', '+', 'g');
			return "https://www.musixmatch.com/ja/lyrics/" + artist + "/" + title;
		}
		
		function onLoaded(request, depth, file) {
			StatusBar.showText((prop.Panel.Lang == 'ja' ? '検索中......' : 'Searching......') + label);
			debug_html && fb.trace('\nOpen#' + depth + ': ' + file + '\n');
			var res = request.responseText;

			debug_html && fb.trace(res);
			var resArray = res.split('\n');
			var Page = new AnalyzePage(resArray, depth);
			
			if (Page.lyrics) {
				var text = onLoaded.info + Page.lyrics;
				debug_html && fb.trace('\n' + text + '\n===End debug=============');
				if (isAutoSearch) {
					plugins['splugin_AutoSearch'].results.push({ name: label, lyric: text });
				}
				else {
					main(text);
					StatusBar.showText(prop.Panel.Lang == 'ja' ? '検索終了。歌詞を取得しました。' : 'Search completed.');
					var AutoSaveTo = window.GetProperty('Plugin.Search.AutoSaveTo');
	
					if (/^Tag$/i.test(AutoSaveTo))
						saveToTag(getFieldName());
					else if (/^File$/i.test(AutoSaveTo))
						saveToFile(parse_path + (filetype === 'lrc' ? '.lrc' : '.txt'));
				}
			}
			else {
				if (isAutoSearch) {
					plugins['splugin_AutoSearch'].results.push({ name: label, lyric: null });
					return;
				}
				StatusBar.hide();
				var intButton = ws.Popup(prop.Panel.Lang == 'ja' ? 'ページが見つかりませんでした。\nブラウザで開きますか？' : 'Page not found.\nOpen the URL in browser?', 0, 'Confirm', 36);
				if (intButton === 6)
					FuncCommand('"' + file + '"');
			}
		}

		function AnalyzePage(resArray, depth) {
			var isLyric = false;
			var StartLyricRE = /"lyrics":\{"id":.+?"body":"(.+?)","language":"(.+?)"/i;
			var LineBreakRE = /\\n/ig;
			var LineFeedCode = prop.Save.LineFeedCode;

			onLoaded.info = title + LineFeedCode + LineFeedCode;
			this.lyrics = '';
			for (var i = 0; i < resArray.length; i++){
				if (StartLyricRE.test(resArray[i])) {
					this.lyrics = RegExp.$1 + LineFeedCode;
					break;
				}
			}
			this.lyrics = this.lyrics
							.replace(LineBreakRE, LineFeedCode)
							.replaceEach('&quot;', '"', '&amp;', '&', 'ig')
							.trim();
		}
	}
};
