import {
  isIpad,
  isIpod,
  isIphone,
  isWindows,
  isMac,
  isWechat,
} from "./isTerminal";
/**
 * 动态加载script
 * @param {string} url
 * @param {string} callback
 */
export function loadScript(url, callback) {
  let script = document.createElement("script");
  if (script.readyState) {
    // IE
    script.onreadystatechange = function () {
      if (script.readyState === "loaded" || script.readyState === "complete") {
        script.onreadystatechange = null;
        callback();
      }
    };
  } else {
    // 其他浏览器
    script.onload = function () {
      callback();
    };
  }
  script.src = url;
  document.getElementsByTagName("head")[0].appendChild(script);
}

/**
 * 闪视频登录状态
 * @param {function} next
 * @returns
 */
export function getUser(next) {
  window.$shanshipin = {};
  // 判断闪视频登录状态
  if (isWindows || isMac || isWechat) return next && next();
  // 获取登录信息
  if (isIpad || isIpod || isIphone) {
    if (!window.webkit || !window.webkit.messageHandlers) return next && next();
    window.setUser = user => {
      if (user == "{}")
        return window.webkit.messageHandlers.iosJumpLogin.postMessage([]);
      const u1 = JSON.parse(user || "{}");
      window.webkit.messageHandlers.getAppInfo.postMessage([]);
      window.setAppInfo = userJson => {
        const u2 = JSON.parse(userJson || "{}");
        window.$shanshipin = {
          ...u1,
          ...u2,
        };
        next && next();
      };
    };

    window.webkit.messageHandlers.tideGetUser.postMessage([]);
  } else {
    if (!window.TideApp) return next && next();
    const u1 = JSON.parse(window.TideApp.getUser() || "{}");
    if (!u1.UserId) window.TideApp.login();
    const u2 = JSON.parse(window.TideApp.getAppInfo() || "{}");
    window.$shanshipin = {
      ...u1,
      ...u2,
    };
    next && next();
  }
}

/**
 * 帧动画
 * @returns 
 */
export function requestAnimationFrame() {
  return (
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame /* Safari 和 Chrome */ ||
    window.mozRequestAnimationFrame /* Firefox */ ||
    window.oRequestAnimationFrame /* Opera */ ||
    window.msRequestAnimationFrame /* IE 9 */ ||
    function (callback) {
      window.setTimeout(callback, 6000 / 60);
    }
  );
}
