const addDataToStorge = data => {
	function getStorage(key) {
		const item = window.localStorage.getItem(key);
		try {
			return item ? JSON.parse(item) : [];
		} catch (e) {
			return item;
		}
	}

	function setStorage(key, value) {
		return window.localStorage.setItem(key, JSON.stringify(value) || '');
	}

	try {
		let allData = getStorage('denetCardData');
		if (
			data.short_url &&
			(data.post_Id || data.invite_code) &&
			!allData.find(item => item.short_url === data.short_url)
		) {
			allData.push(data);
			console.log('addDataToStorge', allData);
			setStorage('denetCardData', allData);
			return true;
		}
	} catch (error) {
		console.log('error', error);
	}
};

const addDom = () => {
	window.denetJS = {};
	window.denetJS.parseAllDeNetCard = () => {
		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 (_txt.includes('#DeNet') || _txt.includes('#DNFT')) {
					de_net_card.push({
						time: new Date().getTime(),
						dom: arr_article[i],
					});
				}
			}
		} catch (error) {
			console.log(error);
		}
		return de_net_card;
	};
	window.denetJS.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 };
	};
	function parseAllDeNetCardParmas() {
		let json_data = [];
		window.denetJS.parseAllDeNetCard().forEach(item => {
			let _obj = window.denetJS.parseCardParmas(item.dom);
			if (_obj.tweet_Id && _obj.short_url && _obj.dom_card) {
				_obj.time = item.time;
				json_data.push(_obj);
			}
		});
		return json_data;
	}
	window.denetJS.toRedpackPage = item => {
		window.ReactNativeWebView.postMessage(
			JSON.stringify({
				actionType: 'goDetailPage',
				data: {
					...item,
					ct0: window.denetJS.getCookie('ct0'),
				},
			}),
		);
		window.event.stopPropagation();
		// window.location.href = 'denet://redpack';
	};
	window.denetJS.getCookie = name => {
		var strcookie = document.cookie; //获取cookie字符串
		var arrcookie = strcookie.split('; '); //分割
		//遍历匹配
		for (var i = 0; i < arrcookie.length; i++) {
			var arr = arrcookie[i].split('=');
			if (arr[0] == name) {
				return arr[1];
			}
		}
		return '';
	};

	window.denetJS.TwitterLikeAPI = (id1, id2) => {
		alert(`${id1}${id2}`);
		fetch(
			'https://mobile.twitter.com/i/api/graphql/lI07N6Otwv1PhnEgXILM7A/FavoriteTweet',
			{
				headers: {
					accept: '*/*',
					'accept-language': 'zh-CN,zh;q=0.9',
					authorization:
						'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
					'cache-control': 'no-cache',
					'content-type': 'application/json',
					pragma: 'no-cache',
					'sec-fetch-dest': 'document',
					'sec-fetch-mode': 'cors',
					'sec-fetch-site': 'same-origin',
					'x-csrf-token': window.denetJS.getCookie('ct0'),
					'x-twitter-active-user': 'yes',
					'x-twitter-auth-type': 'OAuth2Session',
					'x-twitter-client-language': 'zh-cn',
				},
				referrer:
					'https://mobile.twitter.com/laoghaire99/status/1559470845076000769',
				referrerPolicy: 'strict-origin-when-cross-origin',
				body: `{"variables":{"tweet_id":"${id1}${id2}"},"queryId":"lI07N6Otwv1PhnEgXILM7A"}`,
				method: 'POST',
				mode: 'cors',
				credentials: 'include',
			},
		)
			.then(res => {
				console.log(res);
				alert('success');
			})
			.catch(e => {
				// alert(window.getCookie('ct0'))
				// alert(e);
			});
	};
	function setStyle(obj, css) {
		for (var atr in css) {
			obj.style[atr] = css[atr];
		}
	}
	function replaceDOMRedPacket(item) {
		const {
			dom_card,
			tweet_Id,
			post_Id,
			time,
			short_url,
			page_type = '',
			invite_code,
		} = item;
		if (!dom_card || !dom_card.parentElement) {
			return;
		}
		let type;
		let dom = dom_card.querySelector('div[aria-labelledby]');
		dom.style.position = 'relative';
		if (dom) {
			for (let i = 0; i < dom.childNodes.length; i++) {
				if (
					dom.childNodes[i].id &&
					dom.childNodes[i].id == 'denet-card'
				) {
					return;
				}
			}
		}
		if (dom) {
			// debugger mode
			let div = document.createElement('div');
			div.addEventListener('click', () => {
				window.denetJS.toRedpackPage({
					tweet_Id,
					post_Id,
					time,
					short_url,
					page_type,
					invite_code,
				});
			});
			div.id = 'denet-card';
			setStyle(div, {
				position: 'absolute',
				width: '100%',
				height: '100%',
				background: 'rgba(0,0,0,.3)',
				'z-index': 1,
				'text-align': 'center',
				color: '#fff',
				'font-size': '30px',
			});
			div.innerText = 'OPEN IT';
			dom.appendChild(div);
		}
	}

	function setStorage(key, value) {
		return window.localStorage.setItem(key, JSON.stringify(value) || '');
	}

	function getStorage(key) {
		const item = window.localStorage.getItem(key);
		try {
			return item ? JSON.parse(item) : '';
		} catch (e) {
			return item;
		}
	}

	function getCardFromStorge(query) {
		return new Promise((res, rej) => {
			const denetCardData = getStorage('denetCardData') || [];
			const thisCardData = denetCardData.find(
				item => item.short_url === query.short_url,
			);
			if (thisCardData) {
				res(thisCardData);
			} else {
				window.ReactNativeWebView.postMessage(
					JSON.stringify({
						actionType: 'fetchPostId',
						data: {
							// dom_card: query.dom_card,
							short_url: query.short_url,
							time: query.time,
							tweet_Id: query.tweet_Id,
						},
					}),
				);
				res(null);
			}
		});
	}

	try {
		let timer = setInterval(() => {
			let card_json_data = parseAllDeNetCardParmas();
			if (card_json_data.length) {
				for (let i = 0; i < card_json_data.length; i++) {
					getCardFromStorge(card_json_data[i]).then(thisCardData => {
						if (
							thisCardData &&
							(thisCardData.post_Id || thisCardData.invite_code)
						) {
							replaceDOMRedPacket({
								...card_json_data[i],
								...thisCardData,
							});
						}
					});
				}
			}
		}, 3000);
	} catch (error) {
		console.log(error);
	}
};

export { addDom, addDataToStorge };
