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

class ParseCard {
    constructor() {

    }
    parseFaceBookCard() {
        let de_net_card = []
        let arr_article = document.querySelectorAll('div[role="article"]') || []
        let _html
        for (let i in arr_article) {
            _html = arr_article[i].innerHTML || ''
            if (_html.includes('denetme.net') && !this.isHasIframeByFacebook(arr_article[i])) {
                de_net_card.push({
                    time: new Date().getTime(),
                    dom: arr_article[i]
                })
            }
        }
        return de_net_card
    }
    // 兼容mask
    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
    }
    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') || this.compatibleMask(arr_article[i])) && !this.isHasIframeByArticle(arr_article[i])) {
                    de_net_card.push({
                        time: new Date().getTime(),
                        dom: arr_article[i]
                    })
                }
            }
        } catch (error) {
        }
        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 }
    }
    parseFaceBookParmas(dom_card) {
        let tweet_Id = ''
        let short_url = ''
        let tweet_author = '';
        let a_arr = dom_card.querySelectorAll('a[role="link"]') || []
        a_arr = Array.from(a_arr).reverse()
        for (let i in a_arr) {
            // 获取推特id
            if (a_arr[i].href.indexOf('facebook.com') > 0 && a_arr[i].href.indexOf('denetme') > 0 && a_arr[i].href.indexOf('nft') == -1) {
                let faceUrl = new URL(a_arr[i].href);
                let faceSearch = new URLSearchParams(faceUrl.search);
                let faceJumpUrl = decodeURIComponent(faceSearch.get('u'));
                if (faceJumpUrl !== 'null') {
                    let urlArr = new URL(faceJumpUrl);
                    let searchArr = new URLSearchParams(urlArr.search);
                    let deUrlParams = searchArr.get('deUrlParams') || '{}';
                    deUrlParams = JSON.parse(deUrlParams);
                    if (!tweet_Id) {
                        tweet_Id = deUrlParams.tweetId;
                    }
                    if (!short_url) {
                        short_url = faceJumpUrl
                    }
                    if (!tweet_author) {
                        tweet_author = deUrlParams.fullName;
                    }
                }
            } else {
                if (a_arr[i].href.indexOf('denetme.net') > 0 && a_arr[i].href.indexOf('nft') == -1) {
                    let urlArr = new URL(a_arr[i].href);
                    let searchArr = new URLSearchParams(urlArr.search);
                    let deUrlParams = searchArr.get('deUrlParams') || '{}';
                    deUrlParams = JSON.parse(deUrlParams);
                    if (!tweet_Id) {
                        tweet_Id = deUrlParams.tweetId;
                    }
                    if (!short_url) {
                        short_url = a_arr[i].href
                    }
                    if (!tweet_author) {
                        tweet_author = deUrlParams.fullName;
                    }
                }
            }
            if (tweet_Id && short_url) {
                break
            }
        }
        return { tweet_Id, short_url, dom_card, tweet_author }
    }
    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
    }
    parseFacebookCardParmas() {
        let json_data = []
        this.parseFaceBookCard().forEach((item) => {
            let _obj = this.parseFaceBookParmas(item.dom)
            if (_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 = '', tweet_author = '' }, if_center = false) {
        let _iframe = document.createElement('iframe')
        let _iframe_url = ''
        let tweet_str = ''
        if (tweet_Id) {
            tweet_str = `&tweetId=${tweet_Id}`
        }
        _iframe.id = post_Id
        _iframe_url =  chrome.runtime.getURL('/iframe/red-packet.html') + `?postId=${post_Id}${tweet_str}&tweet_author=${tweet_author}&window_origin=${window.location.origin}`;
        // debugger mode
        if(window.location.href.includes('denet_debugger')){
            _iframe_url = _iframe_url + '&denet_debugger=1'
        }
        _iframe.src = _iframe_url
        _iframe.style.cssText = 'border:medium none; width:375px; min-height:500px;'
        if (if_center) {
            _iframe.style.cssText = 'border:medium none; width:375px; min-height:500px; display:block; margin:auto;'
        }
        return _iframe
    }
    createNftIframe({ project_Id }) {
        let project_arr = project_Id.split('/');
        let projectId = project_arr[0]
        let _iframe = document.createElement('iframe')
        _iframe.id = project_Id
        _iframe.src = chrome.runtime.getURL('/iframe/nft-card.html') + `?projectId=${projectId}&twitterAccount=${project_arr[1]}`;
        _iframe.style.cssText = 'border:medium none; width:375px; min-height:300px;'
        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 (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
    }
    isHasIframeByFacebook(dom_card) {
        if (!dom_card || !dom_card.parentElement) {
            return
        }
        let arr_iframe = dom_card.querySelectorAll('iframe') || []
        if (arr_iframe.length > 0) {
            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
    }
    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) {
            // debugger mode
            if (window.location.href.includes('denet_debugger')) {
                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 }))
        }
    }
    replaceNftDomRedPacket({ dom_card, tweet_Id, post_Id, time, short_url }) {
        if (!dom_card || !dom_card.parentElement) {
            return
        }
        let dom = dom_card.querySelector('div[aria-labelledby]')
        if (dom) {
            for (let i = 0; i < dom.childNodes.length; i++) {
                if (dom.children[i].tagName.toLowerCase() != 'iframe') {
                    dom.children[i].style.display = 'none'
                }
            }
        } else {
            dom = dom_card.querySelector('div[lang][dir=auto]').parentElement
        }

        dom.style = 'min-height:300px'
        if (dom) {
            let project_Id = post_Id.replace('nft/', '');
            dom.appendChild(this.createNftIframe({ project_Id }))
        }
    }
    replaceFacebookPacket({ dom_card, tweet_Id, short_url, tweet_author }) {
        if (!dom_card || !dom_card.parentElement) {
            return
        }
        let dom = dom_card.querySelector('div[id^=jsc_c_]').parentElement
        dom.style = 'min-height:500px'
        if (dom) {
            for (let i = 0; i < dom.childNodes.length; i++) {
                if (dom.children[i].tagName.toLowerCase() != 'iframe' && (i !== 0)) {
                    dom.children[i].style.display = 'none'
                }
            }

            if (dom.nextElementSibling && dom.nextElementSibling.id && dom.nextElementSibling.id.indexOf('jsc_c_') >= 0) {
                dom.nextElementSibling.style.display = 'none'
            }
            let originUrl = new URL(short_url);
            let post_Id = originUrl.pathname.slice(1);

            dom.appendChild(this.createIframe({ post_Id, tweet_author }, true))
        }
    }
}
export default new ParseCard()