var request = require("request");
var { Config } = require("../lib/Config");
var sha1 = require("sha1");

function Campus(config) {
  this.config = config;
  this.accessToken = {};
  this.getAccessTokenTimer = null;
}

Campus.prototype.GetAccessToken = function () {
  console.log(Config.campusClientId);
  console.log(Config.campusClientSecret);
  var url =
    "https://api.campushoy.com/client/gettoken?client_id=" +
    Config.campusClientId +
    "&client_secret=" +
    Config.campusClientSecret;
  var self = this;
  let option = {
    url: url,
    method: "GET",
    headers: {
      "content-type": "application/json",
    },
  };
  return new Promise((resolve, reject) => {
    request(option, function (error, response, body) {
      console.log(error, body);
      var data = JSON.parse(body);
      if (error) {
        reject(error);
      } else {
        console.log(data.errmsg);
        if (data.errmsg) {
          console.log("无效的clientId或者clientSecret");
          reject(data);
        } else {
          self.accessToken = {
            client_access_token: data.client_access_token,
            expires_in: data.expires_in,
          };
          console.log("当前access_token", JSON.stringify(self.accessToken));
          // 定时重新获取access_token
          clearTimeout(this.getAccessTokenTimer);
          this.getAccessTokenTimer = setTimeout(() => {
            self.GetAccessToken();
          }, 7200 * 1000 - 60000);
          resolve(data);
        }
      }
    });
  });
};

Campus.prototype.GetJsSdkConfig = function (url) {
  const client_id = Config.campusClientId;
  const timestamp = parseInt(new Date().getTime() / 1000);
  const noncestr = Math.random().toString(36).substring(2, 15);

  const self = this;
  let option = {
    url:
      "https://api.campushoy.com/client/get_jsapi_ticket?client_access_token=" +
      self.accessToken.client_access_token,
    method: "GET",
    headers: {
      "content-type": "application/json",
    },
  };
  return new Promise((resolve, reject) => {
    if (
      self.jsApiTicket &&
      self.jsApiTicket.expires_in > parseInt(new Date().getTime() / 1000)
    ) {
      const signature = sha1(
        `jsapi_ticket=${self.jsApiTicket.ticket}&noncestr=${noncestr}&timestamp=${timestamp}&url=${url}`
      );

      resolve({
        data: {
          client_id,
          timestamp,
          noncestr,
          signature,
        },
      });
      return;
    }

    request(option, function (error, response, body) {
      console.log(error, body);
      if (error) {
        reject(error);
      } else {
        const data = JSON.parse(body);
        self.jsApiTicket = data;
        const signature = sha1(
          `jsapi_ticket=${data.ticket}&noncestr=${noncestr}&timestamp=${timestamp}&url=${url}`
        );
        resolve({
          data: {
            client_id,
            timestamp,
            noncestr,
            signature,
          },
        });
      }
    });
  });
};

module.exports = Campus;
