 # distributed under the License is distributed on an "AS-IS" BASIS,
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
-#    limitations under the License.
+# limitations under the License.
 #
+
+{ Log } = rekuire "log/Log"
 
 class Channel
 


        @wss = new (require('ws').Server) { port: @port }
        @wss.on 'connection', (ws) =>
            console.log 'New connection ', ws.upgradeReq.url
            router.dispatch ws.upgradeReq.url, (err, packet) =>
                if not err
                    channelId = packet.params.channelId
                    senderId = packet.params.senderId
                    if senderId
                        @newSenderConnection channelId, senderId, ws
                    else
                        @newReceiverConnection channelId, ws
                else
                    ws.send JSON.stringify
                        type: 'error'

    close: ->
        @rxconn.close() # senders connection close soon

    setReceiverConn: (rxconn) ->
        @rxconn = rxconn
        @rxconn.on 'message', (message) =>
            Log.i 'Receive receiver message : ', message
            messageObj = JSON.parse message
            senderId = messageObj.senderId
            txconn = @txconn[senderId]
            if txconn
                txconn.send JSON.stringify message.data
            else
                @_respReceiverError 'Invalid sender id'

        @rxconn.on 'close', =>
            @rxconn = null
            @_closeSenders()

    addSenderConn: (senderId, senderConn) ->
        if @rxconn
