/*******************************************************************************
    
    Cloud Firewall - a browser extension/addon that allows users to block connections 
    to sites, pages and web resources (images, videos, etc) hosted in major cloud services
    if the user wishes to do so.
    Copyright (C) 2019 Niklas Poslovski
    Copyright (C) 2019 Gokulakrishna Sudharsan

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Home: https://notabug.org/nipos/cloud-firewall
*/


var App = window.App || {};
App.settingsApp = window.App.settingsApp || {};

App.settingsApp.appVersion = "1.0.0";
App.settingsApp.settingsToggles = {};
App.settingsApp.settingsToggles.google = false;
App.settingsApp.settingsToggles.amazon = false;
App.settingsApp.settingsToggles.facebook = false;
App.settingsApp.settingsToggles.apple = false;
App.settingsApp.settingsToggles.microsoft = false;
App.settingsApp.settingsToggles.cloudflare = false;
App.settingsApp.settingsToggles.notInList = false; //always

var languages = ['de','en'];
var helplink;
var privacylink;
if(languages.includes(browser.i18n.getUILanguage())) helplink = 'help.' + browser.i18n.getUILanguage() + '.html';
else helplink = 'help.en.html';

App.settingsApp.doFactoryReset = () => {
  chrome.runtime.sendMessage({
    type: "doFullReset",
    subtype: "fromSettings"
  });
};

App.settingsApp.showresetConfirmation = false;
App.settingsApp.showresetbutton = true;
App.settingsApp.toggleResetwarn = function() {
  App.settingsApp.showresetConfirmation = !App.settingsApp
    .showresetConfirmation;
  App.settingsApp.showresetbutton = !App.settingsApp.showresetbutton;
  if (App.settingsApp.showresetConfirmation) {
    document.getElementById("showresetConfirmation").style.display = App
      .settingsApp.showresetConfirmation
      ? ""
      : "none";
  }
  App.settingsApp.showresetbutton = !App.settingsApp.showresetbutton;
  document.getElementById("toggleResetwarn").style.display = App.settingsApp
    .showresetbutton
    ? ""
    : "none";
};

App.settingsApp.openHelp = function() {
  var url = chrome.extension.getURL(helplink);

  //FIREFOXBUG: Firefox chokes on url:url filter if the url is a moz-extension:// url
  //so we don't use that, do it the more manual way instead.
  chrome.tabs.query(
    {
      currentWindow: true
    },
    function(tabs) {
      for (var i = 0; i < tabs.length; i++) {
        if (tabs[i].url == url) {
          chrome.tabs.update(
            tabs[i].id,
            {
              active: true
            },
            function(tab) {
              //close();
            }
          );
          return;
        }
      }

      chrome.tabs.create({
        url: helplink
      });
    }
  );
};

App.settingsApp.showresetConfirmation = false;

// Shows a message explaining how many redirects were imported.
/*
App.settingsApp.timestamp = new Date();

App.settingsApp.importRedirects = function() {
  var fileInput = document.getElementById("fileInput");
  fileInput.addEventListener("change", function(e) {
    var file = fileInput.files[0];

    var reader = new FileReader();

    reader.onload = function(e) {
      var data;
      try {
        data = JSON.parse(reader.result);
        console.log("Wayback Everywhere: Imported data" + JSON.stringify(data));
      } catch (e) {
        App.settingsApp.showMessage(
          "Failed to parse JSON data, invalid JSON: " +
            (e.message || "").substr(0, 100)
        );
        return;
      }

      if (!data.redirects) {
        App.settingsApp.showMessage(
          'Invalid JSON, missing "redirects" property '
        );
        return;
      }

      if (
        data.createdBy.indexOf("Wayback Everywhere") < 0 ||
        data.redirects[0].description.indexOf("Wayback Everywhere") < 0
      ) {
        App.settingsApp.showMessage(
          "Invalid JSON, this does not seem to be exported from Wayback Everywhere"
        );
        return;
      }

      var imported = 0,
        existing = 0;

      var i = 0;
      var r = new Redirect(data.redirects[i]);
      if (
        App.settingsApp.redirects.some(function(i) {
          return new Redirect(i).equals(r);
        })
      ) {
        existing++;
      } else {
        var arr = [];
        arr.push(r.toObject());

        imported++;
        App.settingsApp.saveChanges2(arr);
      }

      App.settingsApp.showImportedMessage(imported, existing);

      // add above this
    };

    try {
      reader.readAsText(file, "utf-8");
    } catch (e) {
      App.settingsApp.showMessage("Failed to read import file");
    }
  });
};
*/

/*
// Updates the export link with a data url containing all the redirects.
// We want to have the href updated instead of just generated on click to
// allow people to right click and choose Save As...
App.settingsApp.updateExportLink = function() {
  var d = new Date();
  var localtime = d
    .toTimeString()
    .split("GMT")
    .shift("GMT");
  localtime = localtime.trim();
  var localtimezone = d
    .toTimeString()
    .split("(")
    .pop("GMT")
    .replace(")", "");
  localtimezone = localtimezone.trim();
  var day = d.toDateString();
  day = day
    .substring(4)
    .trim()
    .replace(/ /g, ".");
  App.settingsApp.timestamp = day + "_" + localtime + "_" + localtimezone;

  var redirects = App.settingsApp.redirects.map(function(r) {
    return new Redirect(r).toObject();
  });

  var exportObj = {
    createdBy: "Wayback Everywhere v" + chrome.runtime.getManifest().version,
    createdAt: new Date(),
    redirects: redirects
  };

  var json = JSON.stringify(exportObj, null, 4);

  //Using encodeURIComponent here instead of base64 because base64 always messed up our encoding for some reason...
  App.settingsApp.redirectDownload =
    "data:text/plain;charset=utf-8," + encodeURIComponent(json);
  let elem = document.getElementById("exportSettingBtn");
  if (!!elem) {
    elem.href = App.settingsApp.redirectDownload;
    elem.download = elem.download.replace(
      "{{timestamp}}",
      App.settingsApp.timestamp
    );
  }
}; */

/*
App.settingsApp.showImportedMessage = (imported, existing) => {
  if (imported == 0 && existing == 0) {
    App.settingsApp.showMessage("No redirects existed in the file.");
  }
  if (imported > 0 && existing == 0) {
    App.settingsApp.showMessage("Successfully imported settings", true);
  }
  if (imported == 0 && existing > 0) {
    App.settingsApp.showMessage(
      "All redirects in the file already existed and were ignored."
    );
  }
  if (imported > 0 && existing > 0) {
    var m =
      "Successfully imported " +
      imported +
      " redirect" +
      (imported > 1 ? "s" : "") +
      ". ";
    if (existing == 1) {
      m += "1 redirect already existed and was ignored.";
    } else {
      m += existing + " redirects already existed and were ignored.";
    }
    App.settingsApp.showMessage(m, true);
  }
};

*/
notificationsEnabled = true;
chrome.storage.local.get({ notificationsEnabled: true }, function(obj) {
  notificationsEnabled = obj.notificationsEnabled;
  document.getElementById("toggleNotifications").checked = notificationsEnabled;
});

App.settingsApp.toggleNotifications = function() {
  chrome.storage.local.set(
    { notificationsEnabled: !notificationsEnabled },
    function() {
      notificationsEnabled = !notificationsEnabled;
      document.getElementById(
        "toggleNotifications"
      ).checked = notificationsEnabled;
    }
  );
};

App.settingsApp.logging = false;

App.settingsApp.toggleEncryption = function(password) {
  chrome.runtime.sendMessage(
    {
      type: "toggleEncryption",
      subtype: "fromSettings",
      password: password
    },
    function(response) {
      App.settingsApp.showMessage(response, true);
    }
  );
};

chrome.storage.local.get(
  {
    logging: false
  },
  function(obj) {
    App.settingsApp.logging = obj.logging;
    document.getElementById("toggleLogging").checked = App.settingsApp.logging;
  }
);

App.settingsApp.isDecentralEyesUserOption = false;
chrome.storage.local.get({ isDecentralEyesUserOption: false }, function(obj) {
  App.settingsApp.isDecentralEyesUserOption = obj.isDecentralEyesUserOption;
  document.getElementById("toggleDecentraleyes").checked =
    obj.isDecentralEyesUserOption;
});

App.settingsApp.toggleDecentraleyes = function() {
  chrome.storage.local.set(
    { isDecentralEyesUserOption: !App.settingsApp.isDecentralEyesUserOption },
    function() {
      App.settingsApp.isDecentralEyesUserOption = !App.settingsApp
        .isDecentralEyesUserOption;
      if (App.settingsApp.isDecentralEyesUserOption) {
        document.getElementById("NotetoDecentraleyesUsers").style.display = "";
        document.getElementById("NotetoDecentraleyesUsers").scrollIntoView();
        document.getElementById("decentraleyesNote").style.display = "none";
      } else {
        document.getElementById("NotetoDecentraleyesUsers").style.display =
          "none";
      }
    }
  );
};

//cacheSetting true = write cache to local storage as SHA256 hashes
//cacheSetting false = don't write cache to local storage and use only "in-memory cache"
// default is true

App.settingsApp.cacheSetting = true;

chrome.storage.local.get({ cacheType: true }, function(resp) {
  App.settingsApp.cacheSetting = resp.cacheType;
  document.getElementById("toggleOperationMode").checked =
    App.settingsApp.cacheSetting;
  if (!App.settingsApp.cacheSetting) {
    document.getElementById("toggleResetwarn").style.display = "none";
  }
});
App.settingsApp.PersistenceState = true;

chrome.storage.local.get({ shouldPersistRules: true }, function(resp) {
  document.getElementById("toggleRulePersistence").checked =
    resp.shouldPersistRules;
  App.settingsApp.PersistenceState = resp.shouldPersistRules;
});
/* Future release chrome.storage.local.get({
  isCipherCache : false
}, function(obj){
  if(obj.isCipherCache){
          document.querySelector("#enableEncryption").style.display = "none";
          document.querySelector("#disableEncryption").style.display = "";

  } else{
          document.querySelector("#enableEncryption").style.display = "";
          document.querySelector("#disableEncryption").style.display = "none";

  }
});*/

App.settingsApp.toggleLogging = function() {
  chrome.storage.local.get(
    {
      logging: false
    },
    function(obj) {
      chrome.storage.local.set({
        logging: !obj.logging
      });
      App.settingsApp.logging = !obj.logging;

      console.log(
        "Cloud Firewall - logging enabled to .. " + App.settingsApp.logging
      );
      //App.settingsApp.showdebuginfo();
    }
  );
};

App.settingsApp.toggleOperationMode = () => {
  chrome.storage.local.set(
    {
      cacheType: !App.settingsApp.cacheSetting
    },
    function(a) {
      App.settingsApp.cacheSetting = !App.settingsApp.cacheSetting;
      document.getElementById("toggleOperationMode").checked =
        App.settingsApp.cacheSetting;
      if (App.settingsApp.cacheSetting) {
        document.getElementById("toggleResetwarn").style.display = "";
      }
    }
  );
};

App.settingsApp.toggleRulePersistence = async () => {
  try {
    await browser.storage.local.set({
      shouldPersistRules: !App.settingsApp.PersistenceState
    });
    App.settingsApp.PersistenceState = !App.settingsApp.PersistenceState;

    if (App.settingsApp.logging) {
      console.log(
        "Cloud Firewall: shouldPersistRules toggled to " +
          App.settingsApp.PersistenceState
      );
    }
  } catch (e) {
    if (App.settingsApp.logging) {
      console.log(
        "Cloud Firewall: Unable to toggle persistence state for blocking rules"
      );
      return;
    }
  }
};

/*App.settingsApp.doFactoryReset = () => {
  chrome.runtime.sendMessage({
    type: "doFullReset",
    subtype: "fromSettings"
  });
};*/

// Shows a message bar above the list of redirects.
App.settingsApp.showMessage = (message, success, timer, id) => {
  let msgBox = document.getElementById("message-box");
  let incExcmsg = document.getElementById("incExcmsg");
  if (id != null) {
    App.settingsApp.incExcmsg = message;
    incExcmsg.style.display = "";
    incExcmsg.innerText = message;
    incExcmsg.classList = success ? "success" : "error";
  } else {
    App.settingsApp.message = message;
    msgBox.style.display = "";
    msgBox.innerText = message;
    msgBox.classList = success ? "success" : "error";
  }
  if (timer == null) {
    timer = 10;
  }
  //Remove the message in 20 seconds if it hasnt been changed...

  setTimeout(function() {
    if (App.settingsApp.message == message) {
      App.settingsApp.message = null;
      msgBox.style.display = "none";
    }
  }, timer * 1000);
  setTimeout(function() {
    if (App.settingsApp.incExcmsg == message) {
      App.settingsApp.incExcmsg = null;
      incExcmsg.style.display = "none";
    }
  }, timer * 1000);
};
App.settingsApp.getSettingStates = () => {
  browser.storage.local.get({ settingsToggles: {} }, function(obj) {
    // console.log(obj.settingsToggles);
    for (let company in App.settingsApp.settingsToggles) {
      if (company === "notInList") {
        continue;
      }
      if (
        obj.settingsToggles.hasOwnProperty(company) &&
        typeof obj.settingsToggles[company] !== undefined
      ) {
        App.settingsApp.settingsToggles[company] = obj.settingsToggles[company];
    let id = "#switch" + company;
    document.querySelector(id).checked = App.settingsApp["settingsToggles"][company];
      }
    }
  });
};
App.settingsApp.toggle = async company => {
  try {
    let resp = await browser.runtime.sendMessage({
      type: "toggleSetting",
      subtype: "fromSettings",
      domainname: null,
      company: company
    });
    console.log(resp);
  } catch (e) {
    console.log("Toggling rule for " + company + " failed");
  } finally {
    App.settingsApp.getSettingStates();
  }
};

App.settingsApp.toggleCloudSwitch = e => {
  switch (e.target.id) {
    case "switchgoogle":
      App.settingsApp.toggle("google");
      break;
    case "switchamazon":
      App.settingsApp.toggle("amazon");
      break;
    case "switchfacebook":
      App.settingsApp.toggle("facebook");
      break;
    case "switchapple":
      App.settingsApp.toggle("apple");
      break;
    case "switchmicrosoft":
      App.settingsApp.toggle("microsoft");
      break;
    case "switchcloudflare":
      App.settingsApp.toggle("cloudflare");
      break;
  }
};
window.onload = () => {
App.settingsApp.getSettingStates();
document.getElementById("switches").addEventListener("click",App.settingsApp.toggleCloudSwitch);
document.getElementById("toggles").addEventListener("click",App.settingsApp.listenForClicks);
document.getElementById("openHelp").addEventListener("click",function() {App.settingsApp.openHelp()});
};
/*
App.settingsApp.showresetConfirmation = false;
App.settingsApp.showresetbutton = true;
App.settingsApp.toggleResetwarn = function() {
  App.settingsApp.showresetConfirmation = !App.settingsApp
    .showresetConfirmation;
  App.settingsApp.showresetbutton = !App.settingsApp.showresetbutton;
  if (App.settingsApp.showresetConfirmation) {
    document.getElementById("showresetConfirmation").style.display = App
      .settingsApp.showresetConfirmation
      ? ""
      : "none";
  }
  App.settingsApp.showresetbutton = !App.settingsApp.showresetbutton;
  document.getElementById("toggleResetwarn").style.display = App.settingsApp
    .showresetbutton
    ? ""
    : "none";
};

App.settingsApp.toggleDisabled = function(redirect) {
  redirect.disabled = !redirect.disabled;
  App.settingsApp.saveChanges();
};
*/
// (() => {
//   let hidden = {};
//   if (typeof document.hidden !== "undefined") {
//     // Opera 12.10 and Firefox 18 and later support
//     hidden.visibilityChange = "visibilitychange";
//   } else if (typeof document.msHidden !== "undefined") {
//     hidden.visibilityChange = "msvisibilitychange";
//   } else if (typeof document.webkitHidden !== "undefined") {
//     hidden.visibilityChange = "webkitvisibilitychange";
//   }

//   document.addEventListener(
//     hidden.visibilityChange,
//     App.settingsApp.getInitialValues,
//     false
//   );
// })();
