
import 'package:flutter/foundation.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'cache.dart';
import 'dart:convert';
import 'package:web_socket_channel/io.dart';

import '../models/index.dart';
import '../utils/events.dart';

IOWebSocketChannel _channel;


void onDone() {
  print("socket done");
// Fluttertoast.showToast(msg: "服务器连接失败！请进入设置检查服务地址！");
}

void onError(event) {
  print("socket error: " + event.toString());
}

void onData(event) {
  var data = json.decode(event);
  var type = data["type"];
  print(data);
  switch (type) {
    case "pong":
      break;
    case "userOnline":
      Events.fire(UserOnline(UserInfo.fromJson(data["data"])));
      break;
    case "allUsers":
      Events.fire(UserList(data["data"]));
      break;
    case "message":
      var msg = Message.fromJson(data["data"]);
      var newMsg = HttpMessage();
      newMsg.id = msg.id;
      newMsg.mes_type = "visitor";
      newMsg.content = msg.content;
      newMsg.visitor_avator = msg.avator;
      newMsg.visitor_name = msg.name;
      Events.fire(UserMessage(newMsg));
      break;
  }
}

class Socket {

  static void connect () async {
    var host = Cache.get("server");
    var type = Cache.get("server_type") == "http://" ? "ws://" : "wss://";
    var server = type + host + "/chat_server";

    _channel = IOWebSocketChannel.connect(server, pingInterval: Duration(seconds: 10));
    _channel.stream.listen(onData, onDone: onDone, onError: onError);
    onOpen();
  }

  static void onOpen() {
    online();
  }

  static void online() {
    send({
      "type": "kfOnline",
      "data": json.decode(Cache.get("config"))
    });
  }

  static void ping() {
    send({
      "type": "ping",
      "data": ""
    });
  }
  
  static void send(Map<String, dynamic> data) {
    print("send $data");
    _channel?.sink?.add(json.encode(data));
  }

  static void close() {
    _channel?.sink?.close();
  }
}