import React from 'react';
import ReactDOM from 'react-dom';
import * as API from 'js/API';

import log from 'js/utils/log';
import EventEmitter from 'js/events/EventEmitter';
import FetchSocket from 'socketGW';

import ChatConversation from 'components/ChatConversation/ChatConversation';
import IssueConversation from 'components/QATicketConversation/IssueConversation';
import UserActions from 'js/flux/actions/UserActions';
import ConversationActions from 'js/flux/actions/ConversationActions';

class Main extends EventEmitter{
	constructor(token, options) {
		super();
		options = options || {};

		this.token = token;
		this.options = options;
		this.initSocket();

	}

	initSocket() {
		//FetchSocket.connect({socketUrl: `http://${document.location.hostname}:3000`, token: this.token});
		FetchSocket.connect({socketUrl: `https://livechat.vietid.net`, token: this.token});
		//FetchSocket.connect({socketUrl: `wss://livechat.vietid.net`, token: this.token});
		//FetchSocket.connect({socketUrl: `ws://${document.location.hostname}:3000`, token: this.token});
		FetchSocket.on('authenticated', ::this.authenticated);
	}

	render() {
		this.view_.render();
	}

	joinConversation(ele_id, conversation_id, name='ChatConversation') {
		let ele = document.getElementById(ele_id); 

		switch(name) {
			case 'ChatConversation':
				ReactDOM.render(
				  <ChatConversation conversation_id = {conversation_id} maxBubbleWidth ={179}/>,
				  ele
				);
				break;
			case 'IssueConversation':
				ReactDOM.render(
				  <IssueConversation conversation_id = {conversation_id} maxBubbleWidth ={600} heightMessageList={500} messageGroup={this.options.messageGroup} formatGroupMessage= {this.options.formatGroupMessage} userInfo={this.options.userInfo}/>,
				  ele
				);

		}
		
	}

	sendMessage({conversation_id, content, type}) {
		ConversationActions.sendMessage({conversation_id, content, type});
	}

	authenticated() {
		UserActions.getViewer();
		this.trigger('authenticated');

		ConversationActions.subscriptionSystem();
	}
}

let _instance;

let VCChat = function () {

	if (!_instance) {
		_instance = new Main(...arguments);
	}

	return _instance;
};

VCChat.API = API;


if (typeof define === 'function' && define['amd']) {
  define('VCChat', [], function(){ return VCChat; });

// checking that module is an object too because of umdjs/umd#35
} else if (typeof exports === 'object' && typeof module === 'object') {
  module['exports'] = VCChat;
}

window.VCChat = VCChat;

export default VCChat;


