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

var extractTags = () => {
  var url = document.location.href;
  if (!url || !url.match(/^http/)) {
    console.error("Invalid URL : " + url);
    return;
  }

  var data = {
    title: "",
    description: "",
    image: "",
    url: url
  };

  var ogTitle = document.querySelector("meta[property='og:title']");
  if(ogTitle) {
    data.title = ogTitle.getAttribute("content");
  } else {
    data.title = document.title;
  }

  var descriptionTag = document.querySelector("meta[property='og:description']") || document.querySelector("meta[name='description']");
  if(descriptionTag) {
    data.description = descriptionTag.getAttribute("content")
  }

  var imgTag = document.querySelector("meta[property='og:image']") || document.querySelector("meta[property='twitter-image']");
    if(imgTag) {
        data.image = imgTag.getAttribute("content")
    } else {
        imgTag = document.querySelector("link[rel=icon]") || document.querySelector("link[rel=apple-touch-icon]");
        if (imgTag) {
          data.image = imgTag.getAttribute("href");
        }
    }

  return data;
};

function onRequest(request, sender, sendResponse) {
  if (request.action === 'process-page') {
    sendResponse(extractTags())
  }
}

ext.runtime.onMessage.addListener(onRequest);