/* eslint-disable no-undef */
import { guid } from '@/utils/';
import { getStorageData, setStorageData } from '@/storage/index';

// import { chromeExtensionUrl } from '@/uilts/chromeExtension';
const chromeExtensionUrl = '';
// 解析卡片类
// 1.dom匹配
// 2.找出网页匹配 获取twitterid
// 3.获取短链接postid
// 4.渲染iframe twitterid
// 5.获取红包状态页面
// 6.查询twitterid状态
// 7.绑定twitterid

export const compatibleMask = article => {
	let has_denet = false;
	try {
		let arr_span = article.querySelectorAll('span') || [];
		let arr_shadow = [];
		arr_span.forEach(item => {
			if (item.shadowRoot) {
				arr_shadow.push(item.shadowRoot);
			}
		});
		let item;
		for (let i in arr_shadow) {
			item = arr_shadow[i].childNodes;
			if (has_denet) {
				break;
			}
			if (item) {
				for (let j in item) {
					if (
						item[j].innerText &&
						(item[j].innerText.includes('#DeNet') ||
							item[j].innerText.includes('#DNFT'))
					) {
						has_denet = true;
						break;
					}
				}
			}
		}
	} catch (error) {}
	// 是否有#DeNet
	return has_denet;
};

export const parseAllDeNetCardParmas = (has_iframe = false) => {
	let json_data = [];
	parseAllDeNetCard(has_iframe).forEach(item => {
		let _obj = parseCardParmas(item.dom);
		if (_obj && _obj.tweet_Id && _obj.short_url && _obj.dom_card) {
			_obj.time = item.time;
			json_data.push(_obj);
		}
	});
	return json_data;
};

export const parseAllDeNetCard = (has_iframe = false) => {
	let de_net_card = [];
	try {
		let arr_article = document.querySelectorAll('article') || [];
		let _txt;
		for (let i in arr_article) {
			_txt = arr_article[i].innerText || '';
			if (has_iframe) {
				if (
					_txt.includes('#DeNet') ||
					_txt.includes('#DNFT') ||
					compatibleMask(arr_article[i])
				) {
					de_net_card.push({
						time: new Date().getTime(),
						dom: arr_article[i],
					});
				}
			} else {
				if (
					(_txt.includes('#DeNet') ||
						_txt.includes('#DNFT') ||
						compatibleMask(arr_article[i])) &&
					!isHasIframeByArticle(arr_article[i])
				) {
					de_net_card.push({
						time: new Date().getTime(),
						dom: arr_article[i],
					});
				}
			}
		}
	} catch (error) {}
	return de_net_card;
};

export const parseCardParmas = dom_card => {
	let tweet_Id = '';
	let short_url = '';
	let a_arr = dom_card.querySelectorAll('a') || [];
	a_arr = Array.from(a_arr).reverse();
	for (let i in a_arr) {
		// 获取推特id
		if (
			a_arr[i].href &&
			a_arr[i].href.indexOf('/status/') > 0 &&
			!tweet_Id
		) {
			tweet_Id = a_arr[i].href.split('/status/')[1] || '';
			tweet_Id = tweet_Id.split('/')[0];
		}
		if (
			a_arr[i].href &&
			a_arr[i].href.includes('https://t.co') &&
			!short_url
		) {
			short_url = a_arr[i].href;
		}
		if (tweet_Id && short_url) {
			break;
		}
	}
	return { tweet_Id, short_url, dom_card };
};

export const isHasIframeByArticle = dom_card => {
	if (!dom_card || !dom_card.parentElement) {
		return;
	}
	if (dom_card.querySelector('iframe')) {
		let type = 'parnet';
		let dom = dom_card.querySelector('div[aria-labelledby]');
		if (dom) {
			type = 'card';
		} else {
			type = 'txt';
			dom = dom_card.querySelector('div[lang][dir=auto]').parentElement;
		}

		if (type == 'card') {
			let _iframe = dom.querySelectorAll('iframe') || [];
			if (_iframe.length == 0) {
				dom.style.display = 'none';
			}

			if (_iframe.length == 1) {
				for (let i = 0; i < dom.childNodes.length; i++) {
					if (
						dom.childNodes[i].dataset &&
						dom.childNodes[i].dataset.testid &&
						dom.childNodes[i].dataset.testid == 'card.wrapper'
					) {
						dom.children[i].style.display = 'none';
					}
				}
			}
			if (_iframe.length > 1) {
				for (let i = 0; i < _iframe.length; i++) {
					if (i > 0) {
						_iframe[i].remove();
					}
				}
			}
		} else {
			let arr_iframe =
				dom.closest('article').querySelectorAll('iframe') || [];
			if (arr_iframe.length > 1) {
				for (let i = 0; i < arr_iframe.length; i++) {
					if (i > 0) {
						arr_iframe[i].remove();
					}
				}
			}
		}
		return true;
	}
	return false;
};

export const getLocalHasPostIdData = (
	sort_link_data = [],
	card_json_data = [],
) => {
	//
	let has_post_Id_card_data = [];
	card_json_data.forEach(item => {
		let filter_item = sort_link_data.filter(filter => {
			return filter.short_url == item.short_url && filter.post_Id;
		});
		if (filter_item.length > 0) {
			item.post_Id = filter_item[0].post_Id;
			has_post_Id_card_data.push(item);
		}
	});
	return has_post_Id_card_data;
};

export const filterShortUrl = (sort_link_data, card_json_data) => {
	let has = false;
	let need_net_short_urls = [];

	card_json_data.forEach(card_item => {
		has = false;
		sort_link_data.forEach(local_item => {
			if (
				card_item.short_url == local_item.short_url &&
				local_item.post_Id
			) {
				has = true;
			}
		});
		if (!has) {
			need_net_short_urls.push(card_item.short_url);
		}
	});
	// 返回的是没有postid的
	return need_net_short_urls;
};

export const checkShortUrlArraySize = _array => {
	if (new Blob(_array).size >= 1024 * 1024 * 4) {
		_array.splice(0, parseInt(_array.length / 2));
	}
	return _array;
};

// 获取短链接和渲染卡片数据
export const getCardParmas = async card_json_data => {
	let sort_link_data = getStorage('denetCardData') || [];
	// let sort_link_data = await getChromeStorage('cardData') || []
	let has_post_Id_card_data = getLocalHasPostIdData(
		sort_link_data,
		card_json_data,
	);
	let need_net_short_urls = filterShortUrl(sort_link_data, card_json_data);

	// 校验存储大小
	let new_item = checkShortUrlArraySize(sort_link_data);
	if (sort_link_data.length != new_item.length) {
		setStorage('denetCardData', new_item);
	}
	return {
		has_post_Id_card_data,
		need_net_short_urls,
	};
};
