/**
 * Created by rockyl on 2020-04-29.
 */

import {packImages} from "./sheet-pack";
import {editorApi} from "../api";
import generateUUID from "uuid/v4";
import {fetchApi} from "../api/common";

export async function packAssetsGroups(views, assets) {
	let depCountingMap = {};
	for (let view of views) {
		const {explicitDepAssets, implicitDepAssets} = view;
		let depAssets = [...explicitDepAssets, ...implicitDepAssets];
		for (let depAsset of depAssets) {
			if (!depCountingMap.hasOwnProperty(depAsset)) {
				depCountingMap[depAsset] = [];
			}
			depCountingMap[depAsset].push(view.uuid);
		}
	}

	let assetsGroups = {
		common: [],
	};
	for (let asset of assets) {
		let depCountingViews = depCountingMap[asset.uuid];
		if (!depCountingViews) {
			continue;
		}
		let depCounting = depCountingViews.length;
		if (depCounting > 0) {
			if (depCounting > 1) {  //依赖引用数大于1则放入通用分组
				assetsGroups.common.push(asset);
			} else {
				let depView = depCountingViews[0];
				if (!assetsGroups.hasOwnProperty(depView)) {
					assetsGroups[depView] = [];
				}
				assetsGroups[depView].push(asset);
			}
		}
	}

	let ps = [];
	for (let key in assetsGroups) {
		let group = assetsGroups[key];
		ps.push(packAssets(key, group));
	}
	const groups = await Promise.all(ps);
	for (let group of groups) {
		assetsGroups[group.key] = group.assets;
	}

	return assetsGroups;
}

async function getSheetUrlByUUID(uuid) {
	const response = await fetchApi('/api/uuid2url', {
		params: {uuid},
		errMessage: 'Failed to get url',
	});

	return response.url
}

async function packAssets(key, assets) {
	let newAssets = assets.concat();
	if (assets.length === 0) {
		return {
			key,
			assets,
		};
	}

	let failedList = [];
	await packImages(newAssets, {getSheetUrlByUUID});

	await Promise.all(newAssets.map(asset => {
		return new Promise(async (resolve, reject) => {
			try {
				if (asset.file) {
					await uploadSheet(asset).catch(e => {
						failedList.push(asset);
					});
				}

				resolve();
			} catch (e) {
				reject(e);
			}
		})
	}));

	return {
		key,
		assets: newAssets,
	};
}

async function uploadSheet(asset) {
	const {url} = await editorApi.uploadFile(asset.file, true);
	let sheetConfig = {
		file: url,
		type: 'sheet',
		frames: asset.frames,
	};
	let sheetConfigFile = new File([JSON.stringify(sheetConfig)], 'sheet.json', {type: 'plain/text'});

	const {url: sheetConfigUrl} = await editorApi.uploadFile(sheetConfigFile, false, asset.sheetUUID);
	asset.url = sheetConfigUrl;
	asset.uuid = generateUUID();

	delete asset.file;
	delete asset.frames;
	delete asset.sheetUUID;
}
