const domainsKey = Symbol('domains');

export default class DomainService {
  constructor(domains) {
    this[domainsKey] = domains;
  }

  static addPermission(domain) {
    const origins = [`*://${domain}/`];
    return new Promise((resolve, reject) => {
      chrome.permissions.request({ origins }, (granted) => {
        if (chrome.runtime.lastError) {
          reject(chrome.runtime.lastError.message);
          return;
        }
        if (!granted) {
          reject();
          return;
        }
        resolve();
      });
    });
  }

  static deletePermission(domain) {
    const origins = [`*://${domain}/`];
    return new Promise((resolve, reject) => {
      chrome.permissions.remove({ origins }, (removed) => {
        if (chrome.runtime.lastError) {
          reject(chrome.runtime.lastError.message);
          return;
        }
        if (!removed) {
          reject();
          return;
        }
        resolve();
      });
    });
  }

  static normalize(domain) {
    return domain.replace(/^.*?:\/\//, '').split('/')[0];
  }

  get domains() {
    return this[domainsKey];
  }

  set domains(newDomains) {
    // Avoid re-assignment in favor of array.splice to trigger view updates
    this[domainsKey].splice(0, this.domains.length, ...newDomains);
  }

  add(domain) {
    return DomainService.addPermission(domain)
      .then(() => this.domains.push(domain));
  }

  deleteAt(index) {
    const remainingDomains = this.domains.filter((_, i) => i !== index);
    return DomainService.deletePermission(this.domains[index])
      .then(() => (this.domains = remainingDomains));
  }

  restore() {
    return new Promise((resolve, reject) => {
      chrome.permissions.getAll(({ origins = [] }) => {
        if (chrome.runtime.lastError) {
          reject(chrome.runtime.lastError.message);
          return;
        }
        if (origins.length > 0) {
          this.domains = origins.map(DomainService.normalize);
        }
        resolve();
      });
    });
  }
}

@@ -1372,27 +1372,16 @@
 his.
-domains.push(domain
+restore(
 ));%0A
@@ -1409,81 +1409,8 @@
 ) %7B%0A
-    const remainingDomains = this.domains.filter((_, i) =%3E i !== index);%0A
     
@@ -1490,40 +1490,21 @@
  =%3E 
-(
 this.
-domains = remainingDomains
+restore(
 ));%0A
@@ -1748,44 +1748,8 @@
   %7D%0A
-        if (origins.length %3E 0) %7B%0A  
     
@@ -1805,26 +1805,16 @@
 alize);%0A
-        %7D%0A
         

Use .restore() to update view