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

class ParseCard {
    constructor() {

    }
    parseAllDeNetCard() {
        let de_net_card = []
        let arr_article = document.querySelectorAll('article') || []
        let _txt
        for (let i in arr_article) {
            _txt = arr_article[i].innerText || ''
            if (_txt.includes('#DeNet') && !this.isHasIframeByArticle(arr_article[i])) {
                de_net_card.push({
                    time: new Date().getTime(),
                    dom: arr_article[i]
                })
            }
        }
        return de_net_card
    }
    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 }
    }
    hideCard() {
        if (dom.querySelector('iframe')) {
            return
        }
    }
    parseAllDeNetCardParmas() {
        let json_data = []
        this.parseAllDeNetCard().forEach((item) => {
            let _obj = this.parseCardParmas(item.dom)
            if (_obj.tweet_Id && _obj.short_url && _obj.dom_card) {
                _obj.time = item.time
                json_data.push(_obj)
            }
        })
        return json_data
    }
    // 获取短链接和渲染卡片数据
    async getCardParmas(card_json_data) {
        let sort_link_data = await getChromeStorage('cardData') || []
        let has_post_Id_card_data = this.getLocalHasPostIdData(sort_link_data, card_json_data)
        let need_net_short_url = this.filterShortUrl(sort_link_data, card_json_data)

        // 校验存储大小
        let new_item = this.checkShortUrlArraySize(sort_link_data)
        if (sort_link_data.length != new_item.length) {
            setChromeStorage({ cardData: JSON.stringify(new_item) })
        }
        return {
            has_post_Id_card_data,
            need_net_short_url
        }
    }
    filterShortUrl(sort_link_data, card_json_data) {
        let has = false
        let need_net_short_url = []

        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_url.push(card_item.short_url)
            }
        })
        // 返回的是没有postid的
        return need_net_short_url
    }
    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
    }
    checkShortUrlArraySize(_array) {
        if (new Blob(_array).size >= 1024 * 1024) {
            _array.splice(0, parseInt(_array.length / 2))
        }
        return _array
    }

    createIframe(post_Id, tweet_Id) {
        let _iframe = document.createElement('iframe')
        _iframe.id = post_Id
        _iframe.src = chrome.runtime.getURL('/iframe/red-packet.html') + `?postId=${post_Id}&tweetId=${tweet_Id}`;
        _iframe.style.cssText = 'border: medium none; width:375px;min-height:500px;'
        return _iframe
    }
    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.children[i].tagName.toLowerCase() != 'iframe') {
                            dom.children[i].style.display = 'none'
                        }

                    }
                }
                if (_iframe.length > 1) {
                    for (let i = 0; i < _iframe.length; i++) {
                        if (_iframe > 0) {
                            _iframe[i].remove()
                        }
                    }
                }
            }else{
                let _iframe = dom.parentElement.querySelectorAll('iframe') || []
                if (_iframe.length > 1) {
                    for (let i = 0; i < _iframe.length; i++) {
                        if (_iframe > 0) {
                            _iframe[i].remove()
                        }
                    }
                }
            }
            return true
        }
        return false
    }
    replaceDOMRedPacket({ dom_card, tweet_Id, post_Id, time, short_url }) {
        if (!dom_card || !dom_card.parentElement) {
            return
        }
        let type
        let dom = dom_card.querySelector('div[aria-labelledby]')
        if (dom) {
            type = 'card'
            for (let i = 0; i < dom.childNodes.length; i++) {
                if (dom.children[i].tagName.toLowerCase() != 'iframe') {
                    dom.children[i].style.display = 'none'
                }
            }
        } else {
            type = 'txt'
            dom = dom_card.querySelector('div[lang][dir=auto]').parentElement
        }

        dom.style = 'min-height:500px'
        if (dom) {
            // let div = document.createElement('div')
            // div.style.color = 'red'
            // div.innerText = `
            // tweet_Id:${tweet_Id} , 
            // post_Id:${post_Id}
            // 获取dom时间:${time}
            // 短链接：${short_url}
            // 渲染时长:${(new Date().getTime() - time) / 1000}s
            // `
            // dom.parentElement.appendChild(div)
            dom.appendChild(this.createIframe(post_Id, tweet_Id))
        }

    }
}
export default new ParseCard()