import LocalStorageData from "../Engine/Data/LocalStorageData";
import { LanguageManager } from "../FormTableExt/Manage/Language/LanguageManager";
import { ClipsHandleBySoundTable } from "../FormTableExt/TableExt/ClipsHandleBySoundTable";
import BusinessTypeSetting from "../_BusinessTypeSetting/BusinessTypeSetting";
import CSSettingsSDV3 from "./CSSettingsV3";

const { ccclass } = cc._decorator;

@ccclass
export default class LoadingInit {

	private static _instance: LoadingInit = null;
	public static get Instance(): LoadingInit { return this._instance; }
	//#region private
	private _mp3Length: number = 0;
	private _mp3LoadedCount: number = 0;
	private _handlerClips: ClipsHandleBySoundTable = null;
	private _audioClips: cc.AudioClip[] = [];
	//#endregion

	constructor() {
		LoadingInit._instance = this;
		let language: string = LocalStorageData.Instance.Language;
		cc.log("1.language=" + language);
		LanguageManager.UseLanguageUrlStr = language ? language : LanguageManager.UseLanguageUrlStr;
		LanguageManager.UseLanguageUrlStr = LanguageManager.UseLanguageUrlStr ? LanguageManager.UseLanguageUrlStr : CSSettingsSDV3.Language.Lanuage[LanguageManager.DefaultLanguageFormId].Type;
		LocalStorageData.Instance.Language = LanguageManager.UseLanguageUrlStr;
		cc.log("2.language=" + LanguageManager.UseLanguageUrlStr, LocalStorageData.Instance.Language);
		LanguageManager.Init();
	}

	public *LoadMp3AndLanguageInit(_onProgress: Function, _showProgress: Function): IterableIterator<any> {
		this._handlerClips = new ClipsHandleBySoundTable(0);
		if (!this._handlerClips.SoundTable) {
			if (_onProgress) {
				_onProgress();
			}
			return;
		}
		// 配合語系找語音(找不到載英語再找不到用預設語系語音)
		let checkSoundPath: number[] = LanguageManager.SourceIndex != LanguageManager.Type.En ?
			[LanguageManager.SourceIndex, LanguageManager.Type.En, LanguageManager.Type.ZnTw] : [LanguageManager.SourceIndex, LanguageManager.Type.ZnTw];
		let cloumTagString: string = "";
		for (let num of checkSoundPath) {
			cloumTagString = CSSettingsSDV3.Language.Lanuage[num + 1].SoundPath;
			cloumTagString = this._getCloumTag(cloumTagString);
			let checkUrl: string = this._handlerClips.SoundTable.Rows[0][cloumTagString];
			if (checkUrl) {
				this._handlerClips.UseCloumStr = cloumTagString;
				break;
			}
		}
		this._mp3Length = this._handlerClips.SoundTable.Rows.length;
		this._mp3LoadedCount = 0;
		if (_showProgress) {
			_showProgress(this._mp3LoadedCount, this._mp3Length);
		}
		cc.log("使用語音:" + cloumTagString);
		for (let row of this._handlerClips.SoundTable.Rows) {
			let fileUrl: string = row[cloumTagString];
			if (!fileUrl) {
				continue;
			}
			let name: string = fileUrl.substr(fileUrl.lastIndexOf("/") + 1, fileUrl.length);
			fileUrl = BusinessTypeSetting.UsePatch + BusinessTypeSetting.FolderUrlMp3 + fileUrl + ".mp3";
			fileUrl = fileUrl + this._getParam(row.Id);
			cc.assetManager.loadRemote(fileUrl, (err, audioClip) => this._loadMp3Process(err, audioClip, name, _showProgress));
		}
		while (this._mp3LoadedCount !== this._mp3Length) {
			yield null;
		}
		yield* this._checkLoadMp3End();
	}
	private _loadMp3Process(err: Error, res: cc.Asset, name: string, _showProgress: Function): void {
		if (err == null) {
			cc.log("[事件]mp3載入成功:" + name);
			res.name = name;
			this._audioClips.push(<cc.AudioClip>res);
			this._mp3LoadedCount++;
			if (_showProgress) {
				_showProgress(this._mp3LoadedCount, this._mp3Length);
			}
		} else {
			cc.warn("[Error]mp3載入失敗:" + name);
		}
	}
	private *_checkLoadMp3End(): IterableIterator<string> {
		if (this._handlerClips.SoundTable) {
			cc.log("[事件] 取得Common Mp3");
		} else {
			cc.log("[事件] 沒有SoundTable");
		}
		this._handlerClips.HandlerClips(this._audioClips);
		this._audioClips = null;
	}

	private _getCloumTag(cloumStr: string): string {
		let strs: string[] = cloumStr.split("_");
		let newStr: string = "";
		for (let str of strs) {
			newStr += str.substring(0, 1).toUpperCase().concat(str.substring(1).toLowerCase());
		}
		return newStr;
	}
	private _getParam(id: number): string {
		let str: string;
		if (CC_PREVIEW) {
			str = "?v=" + Date.now();
		} else {
			str = "?v=" + CSSettingsSDV3.Sound[id].Version + "";
		}
		return str;
	}
}