const self = require("sdk/self");
const { ToggleButton } = require('sdk/ui/button/toggle');
const { Panel } = require("sdk/panel");
const { watchFunction, watchWorker } = require("./errors");
const ss = require("sdk/simple-storage");
const clipboard = require("sdk/clipboard");
const { AbstractShot } = require("./shared/shot");

const recallButton = ToggleButton({
  id: "pageshot-recall",
  label: "View your shots",
  icon: self.data.url("icons/library-empty.svg"),
  onChange: function (state) {
    if (state.checked) {
      recallPanel.show();
    }
  }
});

const recallPanel = Panel({
  contentURL: self.data.url("shoot-panel.html"),
  contentScriptFile: [self.data.url("panel-bundle.js")],
  contentScriptOptions: {
    type: "recall"
  },
  position: recallButton,
  height: 450,
  width: 400,
  onHide: function () {
    recallButton.state("window", {checked: false});
  }
});

watchWorker(recallPanel);

let panelReady = false;
let panelViewingId = null;
let panelViewingClips = {};

recallPanel.port.on("ready", watchFunction(function () {
  panelReady = true;
  sendIndex();
}));

recallPanel.port.on("copyLink", watchFunction(function (url) {
  if (typeof url != "string") {
    throw new Error("Got copyLink with non-string argument: " + url);
  }
  clipboard.set(url, "text");
}));

recallPanel.port.on("openLink", watchFunction(function (url) {
  require("sdk/tabs").open(url);
  recallPanel.hide();
}));

recallPanel.port.on("selectClip", watchFunction(function (clipId) {
  panelViewingClips[panelViewingId] = clipId;
  sendShot();
}));

recallPanel.port.on("viewShot", watchFunction(function (id) {
  if (! id) {
    throw new Error("Bad viewShot id: " + id);
  }
  let backend = require("main").getBackend();
  let url = backend + "/data/" + id;
  console.log("requesting", url);
  require("sdk/request").Request({
    url: url,
    onComplete: watchFunction(function (response) {
      let json = response.json;
      console.log("got viewShot data", Object.keys(json));
      console.log("clips:", Object.keys(json.clips));
      let clipId = Object.keys(json.clips)[0];
      if (clipId) {
        let clip = json.clips[clipId];
        console.log("clip", clipId, clip.image.url.length);
      }
      let shot = new AbstractShot(backend, id, json);
      panelViewingId = shot.id;
      panelViewingClips[shot.id] = shot.clipNames()[0];
      sendShot(shot);
    })
  }).get();
}));

recallPanel.port.on("viewRecallIndex", watchFunction(function () {
  panelViewingId = null;
  sendIndex();
}));

function sendIndex() {
  if (! panelReady) {
    return;
  }
  let backend = require("main").getBackend();
  recallPanel.port.emit("recallIndex", {
    backend: backend,
    shots: ss.storage.recentShots || []
  });
}

let lastShot;

function sendShot(shot) {
  if (! panelReady) {
    return;
  }
  if (! shot) {
    shot = lastShot;
  }
  let backend = require("main").getBackend();
  recallPanel.port.emit("recallShot", {
    backend: backend,
    id: shot.id,
    shot: shot.asJson(),
    activeClipName: panelViewingClips[shot.id]
  });
}

exports.addRecall = function (shot) {
  let shotJson = {
    id: shot.id,
    clipCount: Object.keys(shot._clips).length,
    shot: shot.asRecallJson()
  };
  let existing = ss.storage.recentShots || [];
  let found = false;
  for (let i=0; i<existing.length; i++) {
    if (existing[i].id == shotJson.id) {
      existing[i] = shotJson;
      found = true;
      break;
    }
  }
  if (! found) {
    existing.splice(0, 0, shotJson);
  }
  ss.storage.recentShots = existing;
  if (! panelViewingId) {
    sendIndex();
  }
  if (panelViewingId == shot.id) {
    sendShot(shot);
  }
};

@@ -159,16 +159,27 @@
 chWorker
+, unhandled
  %7D = req
@@ -1918,33 +1918,656 @@
     
-let json = response.json;
+if (response.status === 404) %7B%0A        let origUrl = getOrigUrlForId(id) %7C%7C backend + id;%0A        origUrl = origUrl.replace(/&/g, %22&amp;%22).replace(/%22/g, %22&quot;%22);%0A        unhandled(%7B%0A          title: %22Shot not found%22,%0A          message: %22The shot has been lost%22,%0A          helpHtml: %60%0A          We are sorry, the shot has been lost from the server.%0A          Go to %3Ca target=%22_blank%22 href=%22$%7BorigUrl%7D%22%3E$%7BorigUrl%7D%3C/a%3E to see the original page.%0A          %60%0A        %7D);%0A        return;%0A      %7D%0A      let json = response.json;%0A      if (! json) %7B%0A        console.error(%22No/null JSON received from server at:%22, url, %22status:%22, response.status);%0A      %7D
 %0A   
@@ -3362,16 +3362,16 @@
 s %7C%7C %5B%5D%0A
-
   %7D);%0A%7D%0A
@@ -3371,16 +3371,182 @@
  %7D);%0A%7D%0A%0A
+function getOrigUrlForId(id) %7B%0A  for (let item of (ss.storage.recentShots %7C%7C %5B%5D)) %7B%0A    if (item.id === id) %7B%0A      return item.shot.url;%0A    %7D%0A  %7D%0A  return null;%0A%7D%0A%0A
 let last

Handle 404s from the server in recall panel (such as when you wipe your database)