/**
 * 获取facebook 用户基本信息
 * @returns 
 */
function getFBProfile() {
	const photo = FBInstant.player.getPhoto()
	const name = FBInstant.player.getName()
	const id = FBInstant.player.getID()
	const contextType = FBInstant.context.getType()
	return JSON.stringify({ photo, name, id, contextType })
}

function getFBProfileWithUid(success, error) {
	const photo = FBInstant.player.getPhoto()
	const name = FBInstant.player.getName()
	const id = FBInstant.player.getID()
	const contextType = FBInstant.context.getType()
	FBInstant.player.getASIDAsync().then((userId) => {
		success(JSON.stringify({ photo, name, id, contextType, userId }))
	}).catch(err => {
		error(JSON.stringify(err))
		console.error(err.message)
	})
}

function getEntryPointData() {
	const data = FBInstant.getEntryPointData();
	return JSON.stringify(data);
}

function getLocale() {
	return FBInstant.getLocale();
}

//IOS, Android, WEB
function getPlatform() {
	return FBInstant.getPlatform()
}

// 分享游戏
function shareGame(data, success, error) {
	FBInstant.shareAsync(JSON.parse(data))
		.then(success)
		.catch((err) => {
			error(JSON.stringify(err))
			console.error(err.message)
		})
}

function logEvent(eventName, valueToSum, parameters) {
	FBInstant.logEvent(eventName, valueToSum, JSON.parse(parameters))
}

function inviteUser(data, success, error) {
	FBInstant.inviteAsync(JSON.parse(data))
		.then(success)
		.catch((err) => {
			error(JSON.stringify(err))
			console.error(err.message)
		})
}

// 检测当前支持广告类型 ["getInterstitialAdAsync", "getRewardedVideoAsync"]
function checkSupportedAds() {
	let supportedAPIs = FBInstant.getSupportedAPIs()
	return JSON.stringify(supportedAPIs);
}

// 加载，展示插屏广告
let preloadedInterstitial = null
function loadInterstitial(id, success, error) {
	//插屏预载
	FBInstant.getInterstitialAdAsync(id)
		.then((res) => {
			preloadedInterstitial = res
			return preloadedInterstitial.loadAsync
		}).then(res => {
			success()
		}).catch((err) => {
			error(err.message);
			console.error(err.message)
		})
}
function showInterstitial(success, error) {
	if (preloadedInterstitial == null) {
		return error("showInterstitial preloadedInterstitial is null")
	}
	//插屏播放
	preloadedInterstitial
		.showAsync()
		.then(success)
		.catch((err) => {
			error(JSON.stringify(err))
			console.error(err.message)
		})
}
// 加载，展示激励视频
let preloadedRewardedVideo = null
function loadRewarded(id, success, error) {
	//激励视频预载
	FBInstant.getRewardedVideoAsync(id)
		.then((res) => {
			preloadedRewardedVideo = res
			return preloadedRewardedVideo.loadAsync
		}).then(res => {
			success()
		}).catch((err) => {
			error(err.message);
			console.error(err.message)
		})
}
function showRewarded(success, error) {
	if (preloadedRewardedVideo == null) {
		return error("showInterstitial preloadedRewardedVideo is null")
	}
	//插屏播放
	preloadedRewardedVideo
		.showAsync()
		.then(success)
		.catch((err) => {
			error(JSON.stringify(err))
			console.error(err.message)
		})
}
// 展示，隐藏banner广告
function showBannerAds(id, success, error) {
	FBInstant.loadBannerAdAsync(id)
		.then(success)
		.catch((err) => {
			error(JSON.stringify(err))
			console.error(err.message)
		})
}
function hideBannerAds(id, success, error) {
	FBInstant.hideBannerAdAsync(id)
		.then(success)
		.catch((err) => {
			error(JSON.stringify(err))
			console.error(err.message)
		})
}

// tournament 相关

function createTournament(initialScore, config, data, success, error) {
	/**
	 * initialScore: number
	 * config: {
	 * title?: string
	 * image?: base64,
	 * sortOrder?: "HIGHER_IS_BETTER"｜ "LOWER_IS_BETTER"
	 * scoreFormat?: "NUMERIC" | "TIME"
	 * endTime?: unix timestamp (seconds)
	 * }
	 * data: {} customized
	 */
	FBInstant.tournament
		.createAsync({
			initialScore,
			config: JSON.parse(config),
			data: JSON.parse(data),
		})
		.then(success)
		.catch((err) => {
			error(JSON.stringify(err))
			console.error(err.message)
		})
}

function postTournamentScore(id, score, success, error) {
	FBInstant.tournament
		.joinAsync(id)
		.then(function () {
			return FBInstant.tournament.postScoreAsync(score);
		})
		.then(success)
		.catch((err) => {
			error(JSON.stringify(err))
			console.error(err.message)
		})
}

function shareTournament(score, data, success, error) {
	//data: customized {}
	FBInstant.tournament
		.shareAsync({
			score,
			data: JSON.parse(data),
		})
		.then(success)
		.catch((err) => {
			error(JSON.stringify(err))
			console.error(err.message)
		})
}

function getCurrentTournament(success, error) {
	FBInstant.getTournamentAsync()
		.then(function (tournament) {
			success(
				JSON.stringify({
					id: tournament.getContextID(),
					endTime: tournament.getEndTime(),
					title: tournament.getTitle(),
					payLoad: tournament.getPayload(),
				})
			)
		})
		.catch((err) => {
			error(JSON.stringify(err))
			console.error(err.message)
		})
}

// player 相关

function fbSetData(data) {
	FBInstant.player.setDataAsync(JSON.parse(data))
}

function fbGetData(keys, success, error) {
	FBInstant.player
		.getDataAsync(JSON.parse(keys))
		.then((res) => {
			success(JSON.stringify(res))
		})
		.catch((err) => {
			error(JSON.stringify(err))
			console.error(err.message)
		})
}

function subscribeBot(success, error) {
	FBInstant.player
		.canSubscribeBotAsync()
		.then((can_subscribe) => {
			if (can_subscribe) {
				return FBInstant.player.subscribeBotAsync()
			}
		})
		.then(success)
		.catch((err) => {
			error(JSON.stringify(err))
			console.error(err.message)
		})
}

function getConnectedPlayersAsync(success, error) {
	//Fetches an array of ConnectedPlayer objects containing information about active players (people who played the game in the last 90 days) that are connected to the current player.
	FBInstant.player.getConnectedPlayersAsync()
		.then(function (res) {
			var players = res.map(function (player) {
				return {
					player_id: player.getID(),
					name: player.getName(),
					picUrl: player.getPhoto()
				}
			})
			success(JSON.stringify(players))
		})
		.catch((err) => {
			error(JSON.stringify(err))
			console.error(err.message)
		})
}

// context 相关

function getContextInfo() {
	return JSON.stringify({
		id: FBInstant.context.getID(),
		type: FBInstant.context.getType(),
	})
}

function chooseContext(success, error) {
	FBInstant.context.chooseAsync({
		filters: ['INCLUDE_EXISTING_CHALLENGES'],
		minSize: 2,
		maxSize: 2,
	}).then(function () {
		var contextInfo = {
			id: FBInstant.context.getID(),
			type: FBInstant.context.getType(),
		}
		console.log("chooseContext after", contextInfo)
		success(JSON.stringify(contextInfo))
	})
	.catch((err) => {
		error(JSON.stringify(err))
		console.error(err.message)
	})
}

function createAsync(playerId, success, error) {
	FBInstant.context
		.createAsync(playerId)
		.then(success)
		.catch((err) => {
			console.log("createAsync error", JSON.stringify(err))
			error(JSON.stringify(err))
		})
}

function sendPlayWith(data, success, error) {
	FBInstant.context
		.chooseAsync(JSON.parse(data))
		.then(success)
		.catch((err) => {
			console.log(err.message)
			error(JSON.stringify(err))
		})
}

function updateAsync(img) {
	FBInstant.updateAsync({
		action: 'CUSTOM',
		cta: 'Join The Fight',
		image: img,
		text: {
			default: 'X just invaded Y\'s village!',
		},
		template: 'VILLAGE_INVASION',
		data: { myReplayData: 'test', date: new Date().getMilliseconds() },
		strategy: 'IMMEDIATE',
		notification: 'NO_PUSH',
	}).then(function () {
		// closes the game after the update is posted.

	});
}