export function qSelect(element) {
  return document.querySelector(element);
}

export function sendMsg(cmd) {
  chrome.runtime.sendMessage({ cmd });
}

export function localSet(name, value) {
  return new Promise((resolve) => {
    const obj = {};
    obj[name] = value;
    chrome.storage.local.set(obj, () => resolve(value));
  });
}

export function localGet(name, isNumber = false) {
  return new Promise((resolve) => {
    const obj = {};
    obj[name] = isNumber ? 0 : ""; //ห้ามแก้ "" เป็น undefined เด็ดขาด
    chrome.storage.local.get(obj, (res) => resolve(res[name]));
  });
}

export function syncSet(name, value) {
  return new Promise((resolve) => {
    const obj = {};
    obj[name] = value;
    chrome.storage.sync.set(obj, () => resolve(value));
  });
}

export function syncGet(name, isNumber = false) {
  return new Promise((resolve) => {
    const obj = {};
    obj[name] = isNumber ? 0 : "";
    chrome.storage.sync.get(obj, (res) => resolve(res[name]));
  });
}

let timeout1;
export function debounce(delay, func, ...arg) {
  clearTimeout(timeout1);
  timeout1 = setTimeout(() => {
    func(...arg);
  }, delay);
}

export function colorHexToRGB(input) {
  const color = input;
  const r = parseInt(color.substr(1, 2), 16);
  const g = parseInt(color.substr(3, 2), 16);
  const b = parseInt(color.substr(5, 2), 16);
  return `${r},${g},${b}`;
}

export function i18n(message) {
  return chrome.i18n.getMessage(message);
}
