const Sortable = require("sortablejs");
const $ = require("jquery");

const { remote, ipcRenderer } = require("electron");

let sortableObj = null;
let sortableEle = null;

const setTranslateBoxState = (isFloat) => {
  if (isFloat) {
    $("#trans-box").addClass("trans-box-right");
    $(".trans-state img").attr("src", "./images/icons/icon-float.svg");
  } else {
    $("#trans-box").removeClass("trans-box-right");
    $(".trans-state img").attr("src", "./images/icons/icon-static.svg");
    const isDeepl =
      $("#trans-warp webview").attr("src") && $("#trans-warp webview").attr("src").indexOf("deepl.com") > -1;
    const isCaiyun = $("#trans-warp webview").attr("src") && $("#trans-warp webview").attr("src").indexOf("caiyunapp.com") > -1;
    const width = isDeepl || isCaiyun ? 650 : 375;
    $("#trans-warp").css({ width });
    $("#trans-box").css({
      transform: `translate(0px, 0px) scale(1)`,
    });
  }
};

const setOtherBoxState = (isFloat) => {
  if (isFloat) {
    $("#other-box").addClass("other-box-right");
    $(".other-state img").attr("src", "./images/icons/icon-float.svg");
  } else {
    $("#other-box").removeClass("other-box-right");
    $(".other-state img").attr("src", "./images/icons/icon-static.svg");
    const width = 375;
    $("#otherUrl-warp").css({ width });
    $("#other-box").css({
      transform: `translate(0px, 0px) scale(1)`,
    });
  }
};

const initTabDrag = (tabGroup) => {
  if (sortableObj && sortableObj.destroy) {
    sortableObj.destroy();
    sortableEle = null;
  }
  sortableEle = document.getElementById("etabs-tabs");
  sortableObj = new Sortable(sortableEle, {
    // filter: ".home-tab",
    // preventOnFilter: false
    // 结束拖拽
    onEnd: function (/**Event*/ evt) {
      const { oldIndex, newIndex } = evt;
      const $tab = $(evt.item);
      const id = $tab.attr("data-id");
      const tab = tabGroup.getTab(+id);

      if (tab.isHome || oldIndex != newIndex) {
        return;
      }

      let { src, target } = tab.webviewAttributes;
      const link = src || target;

      const isFir =
        link.indexOf("qinyanai.com") > -1 || link.indexOf("localhost") > -1;
      let params = {
        width: 1000,
        height: 800,
      };
      if (isFir) {
        params.webPreferences = {
          nodeIntegration: true,
          contextIsolation: false,
          webviewTag: true,
          enableRemoteModule: true,
        };
      }

      let win = new remote.BrowserWindow(params);
      ipcRenderer.send("setWindow", win.id);

      win.loadURL(link);
      win.on("close", function () {
        ipcRenderer.send("closedWindow", { id: win.id });
        win = null;
      });

      tab.close();
    },
  });
};

module.exports = {
  setTranslateBoxState,
  initTabDrag,
  setOtherBoxState,
};
