'use strict';

angular.module('app').controller('PeerController', ['$scope', '$state', function($scope, $state) {

    lxtalkClient.Invoke('{C62F6059-7741-4AC1-8B8F-97EB5F7C116C}', '_Register', '', $scope);
    var onConnected = function(c){
        c.on('data', function(data) {
            //to do
        });
        c.on('close', function() {
            delete $scope.connectedPeers[c.peer];
        });
        $scope.connectedPeers[c.peer] = 1;
    };

    $scope.init = function(jsonStr){
        var data = JSON.parse(jsonStr);
        // $scope.peer = new Peer(
        //     {
        //         config:{
        //             'iceServers': [
        //                 { 
        //                     'url': 'stun:lqq@59.110.63.164', 
        //                     "credential":"123456" 
        //                 },
        //                 {
        //                     "url":"turn:lqq@59.110.63.164", 
        //                     "credential":"123456"
        //                 }
        //             ]},
        //         key: data.loginName
        //     }        
        // );
        // $scope.connectedPeers = {};
        // $scope.peer.on('open', function(id){console.log(id);});
        // $scope.peer.on('connection', onConnected);
        // $scope.peer.on('error', function(err){console.log(err);});
    };

    $scope.connect = function(jsonStr){
        var data = JSON.parse(jsonStr);
        if (!$scope.connectedPeers[data.loginName]) {
            var c = $scope.peer.connect(data.loginName, data);
            c.on('open', function(){onConnected(c);});
            c.on('error', function(err){console.log(err);});
            $scope.connectedPeers[data.loginName] = 1;
        }
    };

    $scope.send = function(jsonStr, data){
        // var param = JSON.parse(jsonStr);
        var buf = new Uint8Array(data);
        var str = utf8.bytesToString(buf);//new TextDecoder().decode(uint8array); data.toString('utf8')//String.fromCharCode.apply(null, buf);
        
        console.info(str);
        var blob = new Blob(buf)
        // var c = $scope.peer.connections[param.loginName];
        // if (c){
        //     c.send(new Blob(data));
        // }

        var reader = new FileReader();
        reader.readAsText(blob, 'utf-8');
        reader.onload = function (e) {
            console.info(reader.result);
        }
    };

    $scope.close = function(jsonStr){
        var c = $scope.peer.connections[param.loginName];
        if (c){
            c.close();
        }
    };

    $scope.closeAll = function(jsonStr){
        _.forEach($scope.peer.connections, function(c) {
            c.close();
        });
    };

    $scope.destroy = function(jsonStr){
        $scope.peer.destroy();
    };
}]);