var Server = require('socket.io');
var system = require('../base/system');
var redisClient = system.getObject("util.redisClient");
const redisAdapter = require('socket.io-redis');
const uuidv4 = require('uuid/v4');
// const notifyCtl = system.getObject("web.socketNotifyCtl");
// const msgHistoryService = system.getObject("service.msghistorySve");
class MsgHandler {
  constructor(server, client) {
    this.server = server;
    this.client = client;
    this.init();
  }
  notifyClient (ukchannel, msg) {
    var msgH = { msgType: "system", sender: "s￥s￥s￥s", target: msg.to, content: msg.content };
    msgHistoryService.create(msgH).then((m) => {
      redisClient.publish(ukchannel, JSON.stringify(msg));
    }).catch(e => {
      console.log(e);
    });
  }
  init () {
    var self = this;
    //转发通信消息
    this.client.on("chatmsg", msg => {
      const from = msg.from;
      const to = msg.to;
      const msgContent = msg.content;
      var arrs = to.split("￥");
      var tochannel = arrs[0] + "￥" + arrs[1];
      //发布消息
      //持久化消息
      var msgH = { msgType: "single", sender: msg.from, target: msg.to, content: msg.content };
      msgHistoryService.create(msgH).then((m) => {
        redisClient.publish(tochannel, JSON.stringify(msg));
      }).catch(e => {
        console.log(e);
      });
      //self.server.users[to].emit("chatmsg",msg);
    });

    //响应消息处理
    this.client.on("replymsg", (msg, fn) => {
      var p = null;
      var invokeObj = system.getObject("web." + msg.pkgname + "." + msg.cls);
      if (invokeObj[msg.method]) {
        p = invokeObj[msg.method].apply(invokeObj, [msg.data]);
      }
      p.then(r => {
        fn(r);
      }).then(() => {
        console.log("call success")
      }).catch(err => {
        console.log(err)
      })
    });
  }

}
class SocketServer {
  constructor(httpServer) {
    this.server = Server(httpServer, {
      serveClient: false,
      cookie: true
    });
    // this.server.adapter(redisAdapter({ pubClient: redisClient.client, subClient: redisClient.subclient }));
    this.server.engine.generateId = (req) => {
      // console.log(req.headers)
      return "custom:id:" + this.getUUID(); // custom id must be unique
    }
    this.init()
  }
  getUUID () {
    var uuid = uuidv4();
    var u = uuid.replace(/\-/g, "");
    return u;
  }
  init () {
    var self = this.server;
    this.server.on('connection', function (client) {
      console.log("connection.....socket");
      client.on("login", (d) => {
        console.log(d)
      })
      //
      self.of('/').adapter.clients((err, clients) => {
        console.log(clients); // an array containing all connected socket ids
      });
      //链接断开事件
      client.on('disconnect', async function (r) {
        console.log("connection.........................................dismiss.............", client.id, r);
      });
    });
  }

}
module.exports = SocketServer;
