ig.module(
          'plugins.impactconnect'
)
.requires(
          'impact.impact'
)

.defines(function() {
    ig.Impactconnect = ig.Class.extend({
        
        init : function(port) {
            this.remoteId;
            
            try {
                //this.socket = new WebSocket("ws:37.191.206.3:13337/websocket");
                this.socket = io.connect('85.25.116.181:' + port, {
                //this.socket = io.connect('http://localhost:' + port, {
                //this.socket = io.connect('192.168.56.1:' + port, {
                    'reconnect' : true,
                    'reconnection delay' : 500,
                    'max reconnection arrempts' : 10
                });
            } catch(err) {
                // Print error messages.
               
               console.log(err);
               console.log("Error: attempt to connect to server failed!")
               // If connection failed, return.
               return;
            }    
                
            // If attempt to connect to the server was successful, set connected to true.
            ig.game.is_connected = true;

            this.socket.on('setid', function(data) {
                try {
                    console.log("Setting my id to " + data.id);
                    ig.game.my_id = data.id;
                } catch(e) {
                    console.log("catched: " + e);  
                }
            });

            this.socket.on('createGame', function(data){
                try {
                    ig.game.host = true;
                    ig.game.roomid = data.key;
                } catch(e) {
                    console.log("catched: " + e);  
                }
            });

            this.socket.on('joinGame', function(data) {
                try {
                    if(data.res) {
                        ig.game.joinedGame();
                    } else {
                        ig.game.failedtojoin = true;
                    }

                } catch(e) {
                    console.log("catched: " + e);  
                }
            });

            this.socket.on('add', function(data) {
                try {
                    ig.game.others.push(data.id);
                    if(ig.game.debug)
                        console.log("Added a player with id " + data.id + ".");
                } catch(e) {
                    console.log("catched: " + e);  
                }
            });

            this.socket.on('spawn', function(data) {
                if(ig.game.host) return;
                try {
                    if(data.id === ig.game.my_id) {
                        ig.game.state = 4;
                        ig.game.addPlayerPirate(data.id, data.spawnpoint_id);
                        if(ig.game.debug)
                            console.log("Spawn player character at spawn location " + data.spawnpoint_id + ".");
                    } else {
                        ig.game.addOtherPirate(data.id, data.spawnpoint_id);
                        console.log("Spawn remote player at spawn location " + data.spawnpoint_id + ".");
                    };
                } catch(e) {
                    console.log("catched: " + e);   
                }
            });

            // Reeived a "busy" value from a remote user.
            this.socket.on('disconnect', function(data){
                try {
                    console.log("Someone disconnected");
                } catch(e) {
                    //entity null
                    console.log("catched: " + e);
                }
            });

            this.socket.on('state', function(data) {
                if(ig.game.host) return;
                try {
                    var pirates = ig.game.getPirates();

                    for(var i = 0; i < ig.game.pirates.length; i++) {
                        if(ig.game.pirates[i].id === data.id) {
                            if(data.state >= 1 && data.state <= 9) {
                                ig.game.pirates[i].changeStatePos(data.state, data.x, data.y);
                                ig.game.pirates[i].setAngle(data.angle);
                            } else if(data.state === 10) { // Tries to hit.
                                if(ig.game.debug)
                                    console.log("Player " + data.id + " sends input to hit with angle " + data.angle + ".");
                                    ig.game.setPirateHit(data.id, data.angle);
                            }
                        }
                    }
                } catch(e) {
                    //entity null
                    console.log("catched: " + e);
                }
            });

            this.socket.on('key', function(data) {
                if(!ig.game.host) return;
                try {
                    var pirates = ig.game.getPirates();
                    for(var i = 0; i < ig.game.pirates.length; i++) {
                        if(ig.game.pirates[i].id === data.id) {
                            if(data.state >= 1 && data.state <= 9) {
                                ig.game.pirates[i].changeStatePos(data.state, data.x, data.y);
                                ig.game.pirates[i].setAngle(data.angle);

                            } else if(data.state === 10) { // Tries to hit.
                                if(ig.game.debug)
                                    console.log("Player " + data.id + " sends input to hit with angle " + data.angle + ".");
                                    ig.game.setPirateHit(data.id, data.angle);
                            }
                        }
                    }

                    this.send('state', {
                        id:data.id,
                        state:data.state,
                        angle:data.angle,
                        x:data.x,
                        y:data.y,
                        key:data.key
                    });

                } catch(e) {
                    //entity null
                    console.log("catched: " + e);
                }
            });

            this.socket.on('dmg', function(data) {
                if(ig.game.host) return;
                try {
                    var pirates = ig.game.getPirates();

                    for(var i = 0; i < ig.game.pirates.length; i++) {
                        if(ig.game.pirates[i].id === data.id) {
                            ig.game.setPirateGotHit(data.id, data.other_id);
                        }
                    }
                } catch(e) {
                    //entity null
                    console.log("catched: " + e);
                }
            });

            this.socket.on('broadcast', function(data) {
                if(ig.game.host) return;
                switch(data.t) {
                    case "start":
                        ig.game.loadLevel(LevelIsland);
                        if(ig.game.debug)
                            console.log("Loaded level");
                        break;

                    // New chest owner.
                    case "c":
                        ig.game.setNewChestOwner(data.c_id, data.p_id);
                        break;

                    // Spawn coin sack.
                    case "sc":
                        ig.game.spawnCoin(data.id);
                        if(ig.game.debug)
                            console.log("Spawning coin sack at coin spawning point " + data.id + ".");
                        break;

                    // Spawn coin sack.
                    case "sp":
                        ig.game.spawnPotion(data.id);
                        if(ig.game.debug)
                            console.log("Spawning potion at coin spawning point " + data.id + ".");
                         break;

                    // New chest owner.
                    case "pp":
                        ig.game.pickUpPotion(data.index, data.c_id, data.p_id);
                        break;

                                        // New chest owner.
                    case "pc":
                        ig.game.pickUpCoins(data.index, data.c_id, data.p_id);
                        break;

                    case "dmg":
                        ig.game.setPirateGotHit(data.id, data.other_id);
                        break;

                    case "hit":
                        ig.game.setPirateHit(data.id, data.angle);
                        break;

                    case "respawn":
                       if(ig.game.host) return;
                            try {
                                var pirates = ig.game.getPirates();
                                for(var i = 0; i < ig.game.pirates.length; i++) {
                                    if(ig.game.pirates[i].id === data.id) {
                                        ig.game.respawnPirate(data.id, data.spawnpoint_id);
                                    }
                                } 
                            } catch(e) {
                                //entity null
                                console.log("catched: " + e);
                            }
                        break;

                    case "time":
                        ig.game.time = data.time;
                    break;
                }
            });

            this.socket.on('item', function(data) {
                if(ig.game.host) return;
                try {
                switch(data.type) {
                    case "coins":

                        break;

                    case "chest":

                        break;

                    case "potion":
                        break;

                    case "spade":
                        break;
                    } 
                } catch(e) {
                    //entity null
                    console.log("catched: " + e);
                }

               // item { id, spawn_id, type(string) } 
            });
        },

        // Broadcast method to other players in the same instance.
        send: function(name, data){
            // Send data if connected to server.
            if(ig.game.is_connected) {
                this.socket.emit(name, data);
            }
        }
    });
});