"use strict";

const obSvc = require('sdk/deprecated/observer-service');
const {Connection} = require('./connection');
const tabEvents = require('./tab/events');
require('ui');

var allConnections = [];
var connectionFilter = function(connection){ return true; };

obSvc.add("http-on-examine-response", function(subject) {
    var connection = new Connection(subject);
    if (connection.valid){
        allConnections.push(connection);
        // FIXME: Save less frequently
        saveConnections();
        if (uiworker && connectionFilter(connection)){
            uiworker.port.emit('connection', connection);
        }
    }
});

tabEvents.on('activate', function(tabinfo){
    var items = currentConnectionsForTab(tabinfo);
    // visualize items
});


function matchesCurrentTab(connection){
    // this is a tabinfo object
    var tabinfo = this;
    if (!tabinfo) return false;
    if (!tabinfo.uri) return false;
    if (tabinfo.uri.spec === mainPage){ return false; }
    return (connection._sourceTab === tabinfo.tab) && (connection.timestamp > tabinfo.loadTime);
}

function currentConnectionsForTab(tabinfo){
    return allConnections.filter(matchesCurrentTab, tabinfo);
}

// START SERIALIZATION
var storage = require("simple-storage").storage;
if (storage.connections){
    allConnections = JSON.parse(storage.connections).map(function(connection){
        connection.__proto__ = Connection.prototype;
        connection.valid = true;
        connection.timestamp = new Date(connection.timestamp);
        return connection;
    });
}
if (!storage.collusionToken){
    storage.collusionToken = require('sdk/util/uuid').uuid().toString();
}
var collusionToken = storage.collusionToken;


function saveConnections(){
    storage.connections = JSON.stringify(allConnections);
}
// END SERIALIZATION

// Handle Private Browsing

let privateBrowsing = require("private-browsing");

  // Clear graph when going into private browsing mode:
privateBrowsing.on("start", function() {
    storage.allConnections = JSON.stringify(allConnections);
    allConnections = [];
});

// Restore original graph when leaving private browsing mode:
privateBrowsing.on("stop", function() {
    if (storage.allConnections) {
        allConnections = JSON.parse(storage.allConnections);
    }
});




require("page-mod").PageMod({
    include: mainPage,
    contentScriptWhen: 'start',
    contentScriptFile: data.url('content-script.js'),
    onAttach: attachToCollusionPage
});


function collusionTabOpened(tab){
    console.log('collusionTabOpened: ', tab);
}

function collusionTabClosed(tab){
    console.log('collusionTabClosed: ', tab);
    // Stop all Collusion processes, close worker(s)
}

function collusionTabReady(tab){
    console.log('collusionTabReady: ', tab);
    // add-on page should be ready to go, attach scripts
    var worker = attachToExistingCollusionPages(tab);
    // worker.port.emit('log', 'collusionTabReady');
    worker.port.emit('init', allConnections || []); // FIXME: Send appropriate data
}

function collusionTabActivate(tab){
    console.log('collusionTabActivate: ', tab);
    // restart any paused processing, send data through that has changed since pause
}

function collusionTabDeactivate(tab){
    console.log('collusionTabDeactivate: ', tab);
    // pause processing, queue data to be processed on reactivate
}




@@ -1183,16 +1183,60 @@
 fo);%0A%7D%0A%0A
+// FIXME: Move persistence into a component%0A
 // START
@@ -1236,29 +1236,27 @@
 / START 
-SERIALIZATION
+PERSISTENCE
 %0Avar sto
@@ -1839,21 +1839,19 @@
 END 
-SERIALIZATION
+PERSISTENCE
 %0A%0A//
@@ -1875,17 +1875,121 @@
 rowsing%0A
-%0A
+// FIXME: Replace below with new private browsing API%0A// FIXME: Move Private browsing to a component%0A%0A// 
 let priv
@@ -2032,18 +2032,21 @@
 ing%22);%0A%0A
+//
   
+ 
 // Clear
@@ -2083,32 +2083,35 @@
  browsing mode:%0A
+// 
 privateBrowsing.
@@ -2131,24 +2131,27 @@
 unction() %7B%0A
+// 
     storage.
@@ -2195,24 +2195,27 @@
 nnections);%0A
+// 
     allConne
@@ -2227,21 +2227,27 @@
 s = %5B%5D;%0A
+// 
 %7D);%0A%0A
+// 
 // Resto
@@ -2300,16 +2300,19 @@
 g mode:%0A
+// 
 privateB
@@ -2339,24 +2339,27 @@
 unction() %7B%0A
+// 
     if (stor
@@ -2376,24 +2376,27 @@
 nections) %7B%0A
+// 
         allC
@@ -2444,27 +2444,57 @@
 tions);%0A
+// 
     %7D%0A
+// 
 %7D);%0A%0A
+// END Private Browsing%0A
 %0A%0A%0Arequi
@@ -2664,24 +2664,113 @@
 onPage%0A%7D);%0A%0A
+// FIXME: Move below into a tab component%0A// And specify what we're trying to do with it%0A
 %0Afunction co

comment out private browsing until reimplemented with new API