
'use strict';

/*
Ctrl + K + Ctrl + 0: fold all levels (namespace, class, method, and block)
Ctrl + K + Ctrl + 1: namespace / @Component(For Angular)
Ctrl + K + Ctrl + 2: class / methods
Ctrl + K + Ctrl + 3: methods / blocks
Ctrl + K + Ctrl + 4: blocks / inner blocks
Ctrl + K + Ctrl + [ or Ctrl + k + ]: current cursor block
Ctrl + K + Ctrl + j: UnFold
 */


chrome.runtime.onInstalled.addListener(async () => {
    const rules = [{
      id: 1,
      action: {
        type: 'modifyHeaders',
        requestHeaders: [{ header: 'Origin', operation: 'remove' }],
      },
      condition: {
        initiatorDomains: [chrome.runtime.id],
        requestMethods: ['post'],
        resourceTypes: ['xmlhttprequest'],
      },
    }];
    await chrome.declarativeNetRequest.updateDynamicRules({
      removeRuleIds: rules.map(r => r.id),
      addRules: rules,
    });
    chrome.storage.local.get('installedTF', function(a) {
        if (!a.installedTF) {
            chrome.storage.local.set({
                'installedTF': true,
				name: "CACTUS TF"
            }, function() {});
        }
    });
});


function getOriginFromUrl(inp) {
    try {
        var url = new URL(inp);
        var full = url.protocol + '//' + url.hostname + (url.port ? ':' + url.port : '');
        return full;
    } catch (e) {
        return "";
    }
}

chrome.action.onClicked.addListener(function(tab) {
  chrome.tabs.create({
    url: chrome.runtime.getURL("index.html")
	,active: !0
  });
  return true
});

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {

    if (request.type == "get") {
        var url = request.url;
        fetch(url)
            .then(response => response.text())
            .then(response => sendResponse(response))
            .catch()
        return true;
    }

    if (request.type == "post") {
        fetch(request.url, {
                method: 'POST',
                headers: {
                    'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
                    'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
                },
                body: request.data
            })
            .then(response => response.text())
            .then(response => sendResponse(response))
            .catch(error => console.log('Error:', error));
        return true;
    }

    if (request.type == "post_upload") {

        //console.log.log(request.data)

        return true;

    }




    console.log(request.type)
    if (request.type === 'getfanpage'){
        new Promise(async resolve => {
            try{
                console.log('url:',request.url);
                console.log('param:',request.param);
                const response = await fetch(request.url, {
                    method: "POST",
                    headers: {
                        'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
                        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
                    },
                    body: new URLSearchParams(request.param),
                });
                const data = await response.text();
                const data2 = data.replace('for (;;);','');
                const modifiedData = data2.replace('{"successful_results":1,"error_results":0,"skipped_results":0}', '');
                console.log('fanpage',modifiedData);
                resolve(modifiedData);
            }catch(error){
                console.log('err',error);
                resolve(error);
            }
        }).then(sendResponse)
    }
    return true; // return true to indicate you want to send a response asynchronously // keeps the message channel open until `sendResponse` is executed

    // if (request.type == 'getfanpage'){
    //     console.log('get fanpage')
    //     //return new Promise(async (resolve) => {
    //         try{
    //             //sendResponse("Service worker processed the message");

    //             const response = await fetch(request.url, {
    //                 method: "POST",
    //                 body: new URLSearchParams(request.param),
    //             });
    //             const data = await response.text();
    //             const data2 = data.replace('for (;;);','');
    //             const modifiedData = data2.replace('{"successful_results":1,"error_results":0,"skipped_results":0}', '');
    //             console.log('fanpage',modifiedData);
    //             //sendResponse({message: "Service worker processed the message"});
                
    //             sendResponse(modifiedData);
    //             //resolve(true);
    //             return true;
    //         }catch(error){
    //             console.log('err',error);
    //             sendResponse(error);
    //             //resolve(true);
    //             return true;
    //             //sendResponse({title: document.title, url: window.location.href})
    //         }
    //     //});
    // }
    //return true;
});

// chrome.runtime.onMessage.addListener(async (msg, sender, sendResponse) => {

//     if(msg.type === 'execute-script') {
//         // Get the current tab.
//         const tabs = await chrome.tabs.query({ active: !0, currentWindow: !0 });
//         const tabId = tabs[0];
//         await chrome.scripting.executeScript({
//           target: { tabId: tabId.id },
//           function: () => {
//             // Apply the style change in the current tab
//           const logo = document.querySelector('img[alt="Google"]');
//           if (logo) {
//               logo.style.transition = 'transform 2s';
//               logo.style.transform = 'rotate(360deg)';
//            }
//           }
//         });
        
//     }
//     sendResponse(true);

//   })



// chrome.runtime.onMessage.addListener(function (message, sender, senderResponse) {
//     if (message.type === "image") {
//       fetch('<https://api.tinify.com/shrink>', {
//         method: 'POST',
//         headers: {
//           'Authorization': `Basic ${btoa('api:xxxxxx')}`,
//           'Content-Type': 'application/json'
//         },
  
//         body: JSON.stringify({source: {url: message.url}})
//       }).then(res => {
//         return res.json();
//       }).then(res => {
//         senderResponse(res);
//       })
//     }
//     return true
// });



// chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
//     if (request.type === 'getfanpage'){
//       new Promise(async resolve => {
//         try{
//           const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
//           const data = await response.text();
//           const data2 = data.replace('for (;;);','');
//           const modifiedData = data2.replace('{"successful_results":1,"error_results":0,"skipped_results":0}', '');
//           console.log('fanpage',modifiedData);
//           resolve(modifiedData);
          
//         }catch(error){
//             console.log('err',error);
//             resolve(error);
//         }
//       }).then(sendResponse)
//     }
//     return true; // return true to indicate you want to send a response asynchronously // keeps the message channel open until `sendResponse` is executed
// });



console.log('Service worker started.');
