document.addEventListener('DOMContentLoaded', function () {
    var getButton = document.getElementById('get-cookies');
    var sendButton = document.getElementById('send-cookies');
    var cookieList = document.getElementById('cookie-list');

    let _cookies = null;
    let cookieData = null;
    getButton.addEventListener('click', function () {
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
            console.log(tabs);
            var url = tabs[0].url;
            chrome.cookies.getAll({ url: url }, function (cookies) {
                _cookies = cookies;
                cookieData = {
                    cookies: _cookies,
                    xUrl: url
                }

                if (url.includes('meituan.com')){
                    chrome.cookies.getAll({ url: 'https://lvyou.meituan.com' }, function (lvyouCookies) {
                        for (var i = 0; i < lvyouCookies.length; i++) {
                            if (lvyouCookies[i].domain === 'lvyou.meituan.com' ){
                                _cookies.push(lvyouCookies[i]);
                            }
                        }
                    });
                }

                cookieList.innerHTML = '';
                let cookiesText = '';
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = cookies[i];
                    var li = document.createElement('li');
                    li.textContent = cookie.name + '=' + cookie.value;
                    cookieList.appendChild(li);
                    cookiesText += li.textContent + '; ';
                }
            });
        });
    });

    sendButton.addEventListener('click', function () {
        fetch('http://192.168.1.2/index/cookies', {
            method: 'POST',
            body: JSON.stringify(cookieData),
            headers: {
                'Content-Type': 'application/json'
            }
        }).then((data)=>{
            // console.log(data)
        }).catch((error)=>{
            // console.error(error)
        })

        fetch('http://127.0.0.1:8787/index/cookies', {
            method: 'POST',
            body: JSON.stringify(cookieData),
            headers: {
                'Content-Type': 'application/json'
            }
        }).then((data)=>{
            // console.log(data)
        }).catch((error)=>{
            // console.error(error)
        })
    });
});
