import ext from "./utils/ext";
import storage from "./utils/storage";

var page_data = {
    title: "",
    description: "",
    image: "",
    comment: "",
    url: document.location.href
};

var popup = document.getElementById("app");
storage.get('color', function(resp) {
  var color = resp.color;
  if(color) {
    popup.style.backgroundColor = color
  }
});

var template = (data) => {
  return (`
  <div class="site-description">
    <h3 class="title">${data.title}</h3>
    <p class="description">${data.description}</p>
    <p class="image"><img src="${data.image}"></p>
    <div>
        <label for="comment">Comment:</label>
        <textarea id="comment" name="comment"></textarea>
    </div>
    <a href="${data.url}" target="_blank" class="url">${data.url}</a>
  </div>
  <div class="action-container">
    <button id="save-btn" class="btn btn-primary">Save</button>
  </div>
  `);
};
var renderMessage = (message) => {
  var displayContainer = document.getElementById("display-container");
  displayContainer.innerHTML = `<p class='message'>${message}</p>`;
};

var renderBookmark = (data) => {
  var displayContainer = document.getElementById("display-container")
  if(data) {
      page_data = data;
      displayContainer.innerHTML = template(data);
  } else {
    renderMessage(ext.browser.i18n.getMessage("cantExtractTitle"));
  }
};

ext.tabs.query({active: true, currentWindow: true}, function(tabs) {
  var activeTab = tabs[0];
  chrome.tabs.sendMessage(activeTab.id, { action: 'process-page' }, renderBookmark);
});

popup.addEventListener("click", function(e) {
  if(e.target && e.target.matches("#save-btn")) {
      e.preventDefault();
      page_data.comment = document.getElementById("comment").innerText;
      // var data = e.target.getAttribute("data-bookmark");
      ext.runtime.sendMessage({action: "perform-save", data: page_data}, function (response) {
          if (response && response.action === "saved") {
              renderMessage(ext.browser.i18n.getMessage("savedSuccessfully"));
          } else {
              renderMessage(ext.browser.i18n.getMessage("unknownError"));
          }
      });
  }
});

var dataMessages = document.querySelectorAll("[data-message]");
[].forEach.call(dataMessages, function(elt) {
    console.log(elt.dataset.message);
    elt.innerHTML = ext.browser.i18n.getMessage(elt.dataset.message);
});

var optionsLink = document.querySelector(".js-options");
optionsLink.addEventListener("click", function(e) {
  e.preventDefault();
  ext.tabs.create({'url': ext.extension.getURL('options.html')});
});
