<commit_before>import Ember from 'ember';
import {Socket} from '../phoenix';

export default Ember.Service.extend(Ember.Evented, {
  socket: null,
  host: "ws:/localhost:4000/socket",
  channels: {},

  getChannel(name) {
    return this.get('channels')[name];
  },

  connect(host, options) {
    if (this.get('socket')) {
      return;
    };

    host = host || this.get('host');
    let socket = new Socket(host, {
      logger: ((kind, msg, data) => {
        let msgData = "";
        try {
          msgData = JSON.stringify(data)
        } catch(e) {
          //wasn't json -- ignore
        }
        this.trigger('socketMessage', {kind: kind, msg: msg, data: msgData });
        //console.log(`${kind}: ${msg}`, data)
      })
    });

    socket.connect(options);

    socket.onOpen(ev => console.log("OPEN", ev))
    socket.onError(ev => console.log("ERROR", ev))
    socket.onClose(e => console.log("CLOSE", e))
    this.set('socket', socket);
  },

  joinChannel(name, type) {
    const socket = this.get('socket')
    const channel = socket.channel(name, {});
    this.get('channels')[name] = channel

    channel.join().receive("ignore", () => console.log(`Channel ${name}: auth error`))
      .receive("ok", () => console.log(`Joined channel ${name}`))
      .after(10000, () => console.log(`Channel ${name} Connection interruption`))
    channel.onError(e => console.log(`Something went wrong (channel: ${name}`, e))
    channel.onClose(e => console.log(`Closed channel ${name}`, e))
    this.loadTopicHandlers(type, channel);
    return channel;
  },

  setChannelCallback(channelName, topic, callback) {
    const channel = this.getChannel(channelName)
    channel.on(topic, msg => {
      callback(msg);
    })
  },
  channelTopicHandlers: [],

  loadTopicHandlers(channelType, channel) {
    const channelHandlers = this.get('channelTopicHandlers');
    const topicHandlers = channelHandlers && channelHandlers[channelType];
    if (Ember.isBlank(topicHandlers) || Ember.isBlank(channel)){
      return;
    }
    Object.keys(topicHandlers).forEach((topic) => {
      channel.on(topic, (response)=> {
        topicHandlers[topic].call(this, response);
      });
    });
  }
});<commit_msg>handle async<commit_after>import Ember from 'ember';
import {Socket} from '../phoenix';

const { log } = Ember.Logger;

export default Ember.Service.extend(Ember.Evented, {
  socket: null,
  host: "ws:/localhost:4000/socket",
  channels: {},
  channelTopicHandlers: [],

  getChannel(name) {
    return this.get('channels')[name];
  },

  connect(host, options) {
    let socket = this.get('socket');
    if (socket) {
      return new Ember.RSVP.Promise(resolve=> { resolve(socket); });
    };

    host = host || this.get('host');
    socket = new Socket(host, {
      logger: ((kind, msg, data) => {
        let msgData = "";
        try {
          msgData = JSON.stringify(data)
        } catch(e) {
          //wasn't json -- ignore
        }
        this.trigger('socketMessage', {kind: kind, msg: msg, data: msgData });
      })
    });
    return new Ember.RSVP.Promise((resolve, reject) => {

      socket.connect(options);

      socket.onOpen(ev => {
        log("OPENER", ev);
        resolve(ev);
        this.set('socket', socket);
      });
      socket.onError(ev => {
        log("ERROR", ev)
        reject(ev);
      });
      socket.onClose(e => log("CLOSE", e))
    });
  },

  joinChannel(name, type) {
    let channel = this.get('channels')[name];
    if (channel) {
      return new Ember.RSVP.Promise(resolve => { resolve(channel) });
    }

    const socket = this.get('socket');
    Ember.assert('You must connect to a socket before joining a channel (call channelService.connect(..)', socket);

    this.set('name', name);
    let done = false;
    return new Ember.RSVP.Promise((resolve, reject)=> {
      channel = socket.channel(name, {});
      channel.join().receive("ok", (response) => {
        if (done) {
          // for some reason receiving an extra ok on the channel join
          return;
        }
        done = true;
        this.get('channels')[name] = channel
        log(`Joined channel ${this.get('name')}`, response);
        channel.onError(e => log(`Something went wrong (channel: ${name}`, e))
        channel.onClose(e => log(`Closed channel ${name}`, e))
        this.loadTopicHandlers(type, channel);
        resolve(channel);
      }).receive("ignore", (error) => {
        log(`Channel ${name}: auth error`)
        reject(error);
      })
    })
  },

  loadTopicHandlers(channelType, channel) {
    const channelHandlers = this.get('channelTopicHandlers');
    const topicHandlers = channelHandlers && channelHandlers[channelType];
    if (Ember.isBlank(topicHandlers) || Ember.isBlank(channel)){
      return;
    }
    Object.keys(topicHandlers).forEach((topic) => {
      channel.on(topic, (response)=> {
        topicHandlers[topic].call(this, response);
      });
    });
  }
});
{'fraction_non_alphanumeric': 0.17228162194875932, 'fraction_numerical': 0.002622553964091184, 'mean_word_length': 2.8315301391035548, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1862122', 'n_tokens_mistral': 1557, 'n_tokens_neox': 1520, 'n_words': 315}