const rules = [
  {
    id: 1,
    priority: 1,
    action: { type: "block" },
    condition: {
      urlFilter: "doubleclick.net",
      resourceTypes: ["script", "image", "xmlhttprequest"]
    }
  },
  {
    id: 2,
    priority: 1,
    action: { type: "block" },
    condition: {
      urlFilter: "googlesyndication.com",
      resourceTypes: ["script", "image"]
    }
  },
  {
  id: 3,
  priority: 1,
  action: { type: "block" },
  condition: {
    domains: [
      "doubleclick.net",
      "googlesyndication.com",
      "googleadservices.com"
    ],
    resourceTypes: ["script", "image", "sub_frame", "xmlhttprequest"]
  }
}
];

const ruleIds = rules.map(rule => rule.id);

function enableBlocking() {
  chrome.declarativeNetRequest.updateDynamicRules({
    removeRuleIds: ruleIds,
    addRules: rules
  });
}

function disableBlocking() {
  chrome.declarativeNetRequest.updateDynamicRules({
    removeRuleIds: ruleIds
  });
}

chrome.runtime.onInstalled.addListener(() => {
  chrome.storage.local.get(["enabled"], data => {
    const enabled = data.enabled !== false;

    chrome.storage.local.set({ enabled });

    if (enabled) {
      enableBlocking();
    } else {
      disableBlocking();
    }
  });
});

chrome.runtime.onMessage.addListener((message) => {
  if (message.type === "SET_ENABLED") {
    if (message.enabled) {
      enableBlocking();
    } else {
      disableBlocking();
    }
  }
});