var HataDurum = false
var isStarted
var PcName = ''
var AmazonUrl = ''
var MagazaAdi = ''
var AmzUrunList = [];
var zarar = 0

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    if (message.Link) {
        window.location.reload()
        setTimeout(function () {
            window.location.reload()
        }, 1000)
    }
    if (message.UygulamaBaslatildi) {
        SekmeBilgileriGonder()
    }
    if (message.PageReload) {
        window.location.reload()
        setTimeout(function () {
            window.location.reload()
        }, 1000)
    }
})

$(document).ready(function () {
    var host = window.location.host
    chrome.storage.sync.get(
        [
            'isStarted',
            'UrunGetirildi',
            'Durum',
            'UrunFiyat',
            'AmazonUrl',
            'UrunFiyat',
            'MagazaAdi',
            'RequestTime',
        ],
        function (item) {
            setTimeout(async function () {
                if (item.isStarted === true) {
                    MagazaAdi = item.MagazaAdi
                    AmazonUrl = item.AmazonUrl
                    console.log('[Spider] isStarted:', item.isStarted, '| Durum:', item.Durum, '| UrunGetirildi:', item.UrunGetirildi, '| Host:', host)

                    if (isCaptchaPage()) {
                        console.log('CAPTCHA sayfası tespit edildi, geçiliyor...')
                        handleCaptchaPage()
                        return
                    }

                    var urll = window.location.href

                    if(item.Durum == 'AppStarted' && host === 'www.amazon.com') {
                        UrunGetir();
                    }

                    if (host === 'clinic.amazon.com' || host === 'health.amazon.com') {
                        UrunZararYaz()
                    }
                    if (host !== 'www.amazon.com') {
                        if (item.UrunGetirildi === false) {
                            UrunGetir()
                            SekmeBilgileriGonder()
                        } else if (item.Durum === 'FiyatKontrol') {
                            if (host === 'www.jqueryscript.net') {
                                UrunGetir()
                            }
                        } else {
                            YanlisUrun()
                        }
                    } else {
                        if (item.Durum === 'FiyatKontrol') {
                            HataKontrolYap(250)
                            var Fiyat = item.UrunFiyat
                            var AmzPageCount = 0
                            AmazonUrl = item.AmazonUrl
                            setTimeout(function () {
                                AmazonFiyatKontrol(Fiyat, AmzPageCount, AmazonUrl)
                                if (isAmazonDogPage()) {
                                    UrunZararYaz()
                                }
                            }, 500)
                        }
                    }
                }
            }, parseInt(item.RequestTime) * 1000)
        }
    )
})
async function UrunGetir() {
    var host = window.location.host
    await clearAmazonCacheFromContent()

    setTimeout(function () {
        chrome.storage.sync.get(['MagazaAdi', 'PcName', 'isStarted', 'ApiUrl'], function (item) {
            if (item.isStarted) {
                localStorage.clear()
                localStorage.removeItem('LSAmazonUrunList')
                var datam = {
                    magazaDeger: item.MagazaAdi,
                    tip: 'newOrderStartSpider',
                    PCAd: item.PcName,
                }
                console.table(datam)
                $.ajax({
                    type: 'post',
                    url: item.ApiUrl + 'ExtensionWebServis/ajaxCall',
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
                    },
                    cache: false,
                    dataType: 'json',
                    data: datam,
                
                    success: function (cevap) {
                console.log('[API Cevap UrunGetir]', cevap)
                        if (cevap.hata == 0) {
                                    setTimeout(function () {
                                        UrunGetir()
                                    }, 5000)

                        } else {
                            if (cevap.result) {
                                var data = cevap.result
                                if (true) {
                                    localStorage.clear()
                                    localStorage.removeItem('LSAmazonUrunList')
                                    chrome.storage.sync.set(
                                        {
                                            UrunID: data.ID,
                                            UrunGetirildi: true,
                                            Durum: 'FiyatKontrol',
                                            UrunFiyat: data.Fiyat,
                                            AmazonUrl: data.AmazonUrl,
                                            UrunAdet: data.Adet,
                                            Isbn: data.Isbn,
                                            AdresEklendi: false,
                                        },
                                        async function () {
                                            localStorage.setItem('Isbn', data.Isbn);
                                            console.table(data)

                                            SekmeAc(data.AmazonUrl)
                                            AmazonUrl = data.AmazonUrl

                                            if (
                                                data.AmazonUrl &&
                                                (host == 'www.amazon.com')
                                            ) {
                                                SekmeKapat(2)
                                            }
                                        }
                                    )
                                } else {
                                    setTimeout(function () {
                                        UrunGetir()
                                    }, 1000)
                                }
                            }
                        }
                    },
                    error: function (req, textStatus, errorThrown) {
                        console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
                        setTimeout(function () {
                                console.log('Yeni Ürüne Geçilecek! UrunListeleriniGonder()')
                                UrunGetir()
                            }, 5000)
                    },
                })
            }
        })
    }, 2000)
}
function YanlisUrun(fiyat = 0) {
    chrome.storage.sync.get(['UrunID', 'ApiUrl'], function (item) {
        var stringArray = []
        $.ajax({
            type: 'post',
            url: item.ApiUrl + 'ExtensionWebServis/ajaxCall',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
            },
            cache: false,
            dataType: 'json',
            data: {
                ID: item.UrunID,

                tip: 'newOrderWrong',
            },
            success: function (cevap) {
                console.log('[API Cevap YanlisUrun]', cevap)
                if (cevap.hata) {
                } else {
                    if (cevap.result) {
                        UrunGetir()
                    }
                }
            },
            error: function (req, textStatus, errorThrown) {
                console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
                setTimeout(function () {
                                console.log('Yeni Ürüne Geçilecek! UrunListeleriniGonder()')
                                YanlisUrun()
                            }, 2000)
            },
        })
    })
}
async function AmazonFiyatKontrol(fiyat, AmzPageCount, AmazonUrl) {
    var Condition = QueryStringOku('condition')
    if (Condition?.indexOf(',') >= 0) {
        Condition = Condition.split(',')
    }

    waitForElement('#aod-container', function () {
        setTimeout(function () {
            var isArray = Array.isArray(Condition)

            if (isArray) {
                ;['usedGood', 'usedVeryGood', 'usedAcceptable', 'usedLikeNew'].forEach(function (item) {
                    var checkbox = document.querySelector('#' + item + ' > div > label > input[type=checkbox]')
                    if (checkbox && checkbox.checked) {
                        document.querySelector('#' + item).click()
                    }
                })

                Condition.forEach(function (cond) {
                    var checkbox = document.querySelector('#' + cond + ' > div > label > input[type=checkbox]')
                    if (checkbox && !checkbox.checked) {
                        document.querySelector('#' + cond).click()
                    }
                })
            } else {
                if (Condition !== 'new') {

                    if (document.querySelector('#usedGood > div > label > input[type=checkbox]').checked)
                        document.querySelector('#usedGood').click()
                    if (document.querySelector('#usedVeryGood > div > label > input[type=checkbox]').checked)
                        document.querySelector('#usedVeryGood').click()
                    if (document.querySelector('#usedAcceptable > div > label > input[type=checkbox]').checked)
                        document.querySelector('#usedAcceptable').click()
                    if (document.querySelector('#usedLikeNew > div > label > input[type=checkbox]').checked)
                        document.querySelector('#usedLikeNew').click()

                    var checkbox = document.querySelector('#' + Condition + ' > div > label > input[type=checkbox]')
                    if (checkbox && !checkbox.checked) {
                        document.querySelector('#' + Condition).click()
                    }
                }
            }
        }, 3000)

        setTimeout(async function () {
            if (
                $(
                    '#rpi-attribute-book_details-isbn10  div.a-section.a-spacing-none.a-text-center.rpi-attribute-value  span'
                ).length
            ) {
                var Isbn10 = $(
                    '#rpi-attribute-book_details-isbn10  div.a-section.a-spacing-none.a-text-center.rpi-attribute-value  span'
                )
                    .text()
                    .trim()
            }

            if (
                $(
                    '#rpi-attribute-book_details-isbn13  div.a-section.a-spacing-none.a-text-center.rpi-attribute-value  span'
                ).length
            ) {
                var Isbn13 = $(
                    '#rpi-attribute-book_details-isbn13  div.a-section.a-spacing-none.a-text-center.rpi-attribute-value  span'
                )
                    .text()
                    .trim()
            }

            var ASIN = 0
            if ($('#detailBulletsWrapper_feature_div')) {
                $('#detailBulletsWrapper_feature_div > ul').each(function () {
                    if ($(this).text().trim().indexOf('ASIN') != -1) {
                        var text = $(this).find('li > span').text()
                        var splitedText = text
                        if (splitedText.length > 1) {
                            var sText = splitedText.split('ASIN:')
                            if (sText.length >= 1 && typeof sText[1] !== 'undefined') {
                                ASIN = sText[1].trim().split('#')[1]
                            }
                        }
                    }
                })
            }

            if ($('#detailBullets_feature_div')) {
                $('#detailBullets_feature_div > ul').each(function () {
                    if ($(this).text().trim().indexOf('ASIN') != -1) {
                        var text = $(this).find('li > span').text()
                        var splitedText = text
                        if (splitedText.length > 1) {
                            var sText = splitedText.split('ASIN:')
                            if (sText.length >= 1 && typeof sText[1] !== 'undefined') {
                                ASIN = sText[1].trim()
                            }
                        }
                    }
                })
            }

            if (ASIN != 0) {
                Isbn10 = ASIN
            }

            var UrunList = localStorage.getItem('LSAmazonUrunList')
            if (UrunList != undefined) {
                AmzUrunList = JSON.parse(UrunList)
            }
            var liste = $('#aod-offer-list #aod-offer')
            var listeItemCount = parseInt($('#aod-offer-list #aod-offer').length) - 1
            
            try {
                chrome.storage.local.set({ Isbn10, Isbn13 });
            } catch (e) {
                window.location.reload();
            }
        
            var FiyatKontrolTamamlandi = true
            liste.each(function (index) {
                var UrunFiyat = $(this)
                    .find('.a-price span[aria-hidden="true"]')
                    .text()
                    .trim()
                    .substr(1)
                    .replace(',', '')
                if (
                    $(this)
                        .find('#mir-layout-DELIVERY_BLOCK-slot-PRIMARY_DELIVERY_MESSAGE_LARGE')
                        .find('span')
                        .attr('data-csa-c-delivery-price')
                ) {
                    var KargoFiyat = $(this)
                        .find('#mir-layout-DELIVERY_BLOCK-slot-PRIMARY_DELIVERY_MESSAGE_LARGE')
                        .find('span')
                        .attr('data-csa-c-delivery-price')
                        .split('$')
                } else {
                    var KargoFiyat = 0.0
                }
                if (KargoFiyat.length > 1 || KargoFiyat[0] !== 'FREE') KargoFiyat = KargoFiyat[1] ?? KargoFiyat
                var DFiyat = parseFloat(fiyat)
                var DUrunFiyat = parseFloat(UrunFiyat)
                var DKargoFiyat = KargoFiyat.length > 1 ? parseFloat(KargoFiyat) : 0
                if (isNaN(DKargoFiyat)) DKargoFiyat = 0.0
                var Price = DUrunFiyat + DKargoFiyat
                var Condition = $(this).find('#aod-offer-heading').text().replace(/\s/g, '').trim()
                var ConditionDesc = $(this).find('#condition-text-block-title span.expandable-expanded-text').text()

                var Seller = $(this).find('#aod-offer-soldBy a').text().trim()
                var Positive = $(this).find('#seller-rating-count-\\{iter\\} > span').text().split('%')
                if (Positive.length > 0) Positive = Positive[0].split(')')[1]
                var r = $(this).find('#seller-rating-count-\\{iter\\} > span').text().split('%')
                if (r.length > 0) r = r[0].split(')')[0].split(' ')[0].split('(')[1]
                var Ratings = r != undefined ? r : '-'
                Price = Price.toFixed(2)

                var item = {
                    index,
                    Condition,
                    Seller,
                    Positive,
                    Ratings,
                    Price,
                    ConditionDesc,
                    Page: AmzPageCount,
                }
                AmzUrunList.push(item)
                if (listeItemCount === index && listeItemCount !== 0) {
                    FiyatKontrolTamamlandi = true
                    localStorage.setItem('LSAmazonUrunList', JSON.stringify(AmzUrunList))
                } else {
                    FiyatKontrolTamamlandi = true
                }
            })
            if (FiyatKontrolTamamlandi) {
                console.table(AmzUrunList)
                chrome.storage.local.set(
                    {
                        AmzUrunList: AmzUrunList,
                        AmazonUrl: AmazonUrl,
                        UrunFiyat: fiyat,
                    },
                    function () {
                        localStorage.removeItem('LSAmazonUrunList')
                        UrunListeleriniGonder()
                    }
                )
            } else {
                var PaginationNext = parseInt(AmzPageCount) + 1
                chrome.storage.sync.set(
                    {
                        AmzPageCount: PaginationNext,
                    },
                    function () {
                        var amzlink = AmazonUrl
                        var params = '&PgNm=Amz&startIndex=' + PaginationNext * 10
                        var link = amzlink + params
                    }
                )
            }
        }, 10000)
    }, 15000, function () {
        console.log('#aod-container bulunamadı (AmazonFiyatKontrol), YanlisUrun...')
        YanlisUrun()
    })
}
function UrunListeleriniGonder() {

    var host = window.location.host
    let OurPrice = 0
    let MagazaAdi = ''
    chrome.storage.sync.get(['UrunID', 'PcName', 'UrunFiyat', 'ApiUrl', 'MagazaAdi'], function (item) {
        UrunID = item.UrunID
        PcName = item.PcName
        OurPrice = item.UrunFiyat
        ApiUrl = item.ApiUrl
        MagazaAdi = item.MagazaAdi
    })
    chrome.storage.local.get(
        [
            'AmzUrunList',
            'PcName',
            'UrunFiyat',
            'Rank',
            'SellerCount',
            'newPrice',
            'Isbn10',
            'Isbn13',
            'buyBoxNew',
            'buyBoxNewPrice',
        ],
        function (item) {
            var Amazon = item.AmzUrunList
            var orderArray = [[...Amazon]]

            var stringArray = JSON.stringify(orderArray)
            var datam = {
                ID: UrunID,
                price: 0,
                magazaDeger: MagazaAdi,
                orderArray: stringArray,
                tip: 'newOrderFiltreSpider',
                PCAd: PcName,
                OurPrice: OurPrice,
                Rank: item.Rank,
                SaticiSayisi: item.SellerCount,
                NewPrice: item.newPrice,
                Isbn10: item.Isbn10,
                Isbn13: item.Isbn13,
                buyBoxNew: item.buyBoxNew,
                buyBoxNewPrice: item.buyBoxNewPrice,
            }

            console.table(datam)
            $.ajax({
                type: 'post',
                url: ApiUrl + 'ExtensionWebServis/ajaxCall',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
                },
                cache: false,
                dataType: 'json',
                timeout: 500000,
                data: datam,
                success: function (cevap) {
                console.log('[API Cevap UrunListeleriniGonder]', cevap)
                    if (cevap.hata) {
                    } else {
                       if (cevap.result) {
                                var gelenJson = cevap.result
                                setTimeout(function () {
                                    console.log('Yeni Ürüne Geçilecek! UrunListeleriniGonder()')
                                    UrunGetir()
                                }, 5000)
                        } else {
                            setTimeout(function () {
                                console.log('Yeni Ürüne Geçilecek! UrunListeleriniGonder()')
                                UrunGetir()
                            }, 5000)
                        }
                    }
                },
                error: function (req, textStatus, errorThrown) {
                    console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
                    setTimeout(function () {
                                console.log('Yeni Ürüne Geçilecek! UrunListeleriniGonder()')
                                UrunListeleriniGonder()
                            }, 5000)
                },
            })
        }
    )
}
function UrunZararYaz(fiyat = 0) {
    chrome.storage.sync.get(['UrunID', 'ApiUrl'], function (item) {
        var stringArray = []
        $.ajax({
            type: 'post',
            url: item.ApiUrl + 'ExtensionWebServis/ajaxCall',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
            },
            cache: false,
            dataType: 'json',
            data: {
                ID: item.UrunID,
                price: fiyat,
                orderArray: stringArray,
                tip: 'newOrderFiltreOtomatik',
            },
            success: function (cevap) {
                console.log('[API Cevap UrunZararYaz]', cevap)
                if (cevap.hata) {
                } else {
                    if (cevap.result == null || cevap.result.length == 0) {
                        UrunGetir()
                    }
                }
            },
            error: function (req, textStatus, errorThrown) {
                console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
                setTimeout(function () {
                                console.log('Yeni Ürüne Geçilecek! UrunListeleriniGonder()')
                                UrunZararYaz()
                }, 5000)
            },
        })
    })
}
async function HataKontrolYap(time, msj2) {
    HataKontrol = setTimeout(async function () {
            try {
                chrome.storage.local.get(['isStarted', 'PcName', 'Durum', 'UrunID', 'MagazaAdi'], function (item) {
                var aciklama = ''
                if (msj2 == undefined) {
                    aciklama = ''
                } else {
                    aciklama = msj2
                }
                var msj = `Bilgisayar: ${item.PcName} Mağaza Adı: ${item.MagazaAdi}  Durum: ${item.Durum} iken extension çalışmayı durdurdu! ${aciklama}`
                var datam = {
                    ID: item.UrunID,
                    tip: 'newOrderBreak',
                    mesaj: msj,
                }
                var host = window.location.host
                chrome.runtime.sendMessage({
                    HataYenile: true,
                })
            })
            } catch (e) {
                window.location.reload();
            }
       
    }, parseInt(time) * 1000)
}
function SekmeBilgileriGonder() {
    chrome.runtime.sendMessage({
        AktifSekmeBilgileri: true,
    })
}
function isAmazonDogPage() {
    const title = document.title.toLowerCase()
    return title.includes('page not found') || title.includes('sorry') || title.includes('went wrong')
}
function isCaptchaPage() {
    return document.querySelector('form[action="/errors/validateCaptcha"]') !== null
        || document.querySelector('#captchacharacters') !== null
        || document.title.toLowerCase().includes('robot check')
}
function handleCaptchaPage() {
    console.log('CAPTCHA sayfası, UrunGetir bekleniyor...')
    setTimeout(function () {
        UrunGetir()
    }, 3000)
}
function waitForAmazonReady(callback) {
    if (document.readyState === 'complete') {
        if (typeof callback === 'function') callback()
    } else {
        window.addEventListener('load', function () {
            if (typeof callback === 'function') callback()
        })
    }
}

function setOrderItemData() {
    var orderItemData = {}
    var orderItemCount = 0
    var newD = false
    if (document.querySelector('#header > div > div.a-column.a-span8 > h1 > span > span > span > span')) {
        orderItemCount = parseInt(
            document
                .querySelector('#header > div > div.a-column.a-span8 > h1 > span > span > span > span')
                .textContent.split(' ')[0]
        )
    }

    if (orderItemCount == 0) {
        newD = true
        orderItemCount = $('.lineitem-container').length
    }

    if (orderItemCount > 10) {
        alert(
            'Lütfen sepeti içerisindeki ürün adeti 10 veya daha küçük olmalıdır aksi takdirde hata oluşacaktır. Sepet içerisinde ürün sayısını azaltıp sayfayı yenileyiniz.'
        )
    }

    var cnt = 0

    if (!newD) {
        $('#spc-orders div.a-box-inner .item-row').each(function () {
            var seller = $(this)
                .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right  div:nth-child(5) > span')
                .text()
                .trim()
                .split('Sold by:')[1]

            if (seller == undefined) {
                seller = $(this)
                    .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right  div:nth-child(6) > span')
                    .text()
                    .trim()
                    .split('Sold by:')[1]
            }

            if (seller == undefined) {
                seller = $(this)
                    .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right  div:nth-child(4) > span')
                    .text()
                    .trim()
                    .split('Sold by:')[1]
            }
            if (seller !== undefined) {
                var condition = undefined
                if (
                    $(this)
                        .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right  div:nth-child(6) span')
                        .text()
                        .trim() != '' &&
                    condition == undefined
                )
                    condition = $(this)
                        .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right  div:nth-child(6) span')
                        .text()
                        .trim()
                        .split('Condition:')[1]
                if (
                    $(this)
                        .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right  div:nth-child(7) span')
                        .text()
                        .trim() != '' &&
                    condition == undefined
                )
                    condition = $(this)
                        .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right  div:nth-child(7) span')
                        .text()
                        .trim()
                        .split('Condition:')[1]
                if (
                    $(this)
                        .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right  div:nth-child(8) span')
                        .text()
                        .trim() != '' &&
                    condition == undefined
                )
                    condition = $(this)
                        .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right  div:nth-child(8) span')
                        .text()
                        .trim()
                        .split('Condition:')[1]
                var title = $(this)
                    .find(
                        'div.a-fixed-left-grid-col.item-details-right-column.a-col-right > div.a-row.breakword > span'
                    )
                    .text()
                var price = $(this)
                    .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right span.a-color-price span')
                    .text()
                var quantity = $(this).find('span.a-dropdown-prompt').text().trim()
                orderItemData[cnt] = {}
                orderItemData[cnt].seller = seller
                orderItemData[cnt].condition = condition
                orderItemData[cnt].quantity = quantity
                orderItemData[cnt].name = title.trim()
                orderItemData[cnt].price = price.trim().split('$')[1]
                cnt++
            }
        })
        console.table(orderItemData)
        localStorage.setItem('OrderItemData', JSON.stringify(orderItemData))
        chrome.storage.local.set(
            {
                OrderItemData: JSON.stringify(orderItemData),
            },
            function () {}
        )
        document.querySelector('#submitOrderButtonId-announce').textContent = 'Siparişi Tamamla'
        chrome.storage.local.get('OrderItemData', function (itemm) {
            'OrderItemData'
        })
    } else {
        $('.lineitem-container').each(function () {
            var seller = removeRepeatingSubstring($(this).find('.lineitem-seller-section a span').text().trim())

            var quantity = $(this).find('.a-box-inner .a-row:nth-child(2) div span:nth-child(2)').text().trim()
            var title = $(this).find('.lineitem-title-text').text().trim()
            var price = $(this).find('.lineitem-price-text').text().trim().split('$')[1]
            var condition = 'Used - Like New'
            orderItemData[cnt] = {}
            orderItemData[cnt].seller = seller
            orderItemData[cnt].condition = condition
            orderItemData[cnt].quantity = quantity
            orderItemData[cnt].name = title
            orderItemData[cnt].price = price
            cnt++
            console.table(orderItemData)
            localStorage.setItem('OrderItemData', JSON.stringify(orderItemData))
            chrome.storage.local.set(
                {
                    OrderItemData: JSON.stringify(orderItemData),
                },
                function () {}
            )
            document.querySelector('#submitOrderButtonId-announce').textContent = 'Siparişi Tamamla'
            chrome.storage.local.get('OrderItemData', function (itemm) {
                'OrderItemData'
            })
        })
    }
}
function SayfaGit(adres, time) {
    setTimeout(function () {
        window.location.href = adres
    }, parseInt(time) * 1000)
}
function clearAmazonCacheFromContent() {
    return new Promise((resolve) => {
        chrome.runtime.sendMessage({ action: 'clearAmazonCache' }, (response) => {
            if (response && response.success) {
            }
            resolve()
        })
    })
}
function SekmeAc(link) {
    setTimeout(function () {
        chrome.runtime.sendMessage({
            YeniSekme: true,
            Url: link,
        })
    }, 200)
}

function SekmeKapat(sure) {
    setTimeout(function () {
        chrome.runtime.sendMessage({
            SekmeKapat: true,
        })
    }, sure * 1000)
}

function QueryStringOku(name, url) {
    if (!url) url = window.location.href
    name = name.replace(/[\[\]]/g, '\\$&')
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url)
    if (!results) return null
    if (!results[2]) return ''
    return decodeURIComponent(results[2].replace(/\+/g, ' '))
}
function waitForElement(elementPath, callBack, timeout, onTimeout) {
    var start = timeout ? Date.now() : null
    function check() {
        if ($(elementPath).text().length > 0) {
            callBack(elementPath, $(elementPath))
        } else if (timeout && (Date.now() - start) >= timeout) {
            console.log('waitForElement timeout: ' + elementPath)
            if (typeof onTimeout === 'function') onTimeout()
        } else {
            window.setTimeout(check, 100)
        }
    }
    window.setTimeout(check, 100)
}
function removeRepeatingSubstring(str) {
    let match = str.match(/^(.+?)\1+$/)
    if (match) {
        return match[1]
    }
    return str
}

function dialogModal(message, background = 'limegreen') {
    let loader = document.createElement('div')
    $(loader).addClass('extDialog')
    $(loader).css('position', 'fixed')
    $(loader).css('min-height', '200px')
    $(loader).css('height', 'auto')
    $(loader).css('width', '200px')
    $(loader).css('background', background)
    $(loader).css('color', '#fff')
    $(loader).css('overflow-wrap', 'anywhere')
    $(loader).css('border-radius', '50%')
    $(loader).css('font-weight', 'bold')
    $(loader).css('bottom', '10px')
    $(loader).css('right', '0')
    $(loader).css('z-index', '9999')
    $(loader).css('display', 'flex')
    $(loader).css('justify-content', 'center')
    $(loader).css('align-items', 'center')
    $(loader).css('padding', '10px 10px 10px 10px')

    $(loader).html(message)
    document.body.append(loader)
    return loader
}
function hasInvalidRecord(data) {
    const dataArray = Object.values(data)
    return dataArray.some(
        (item) => !('orderId' in item) || item.orderId === null || item.orderId === undefined || item.orderId === ''
    )
}