var Client = function(model) {
	var model = model;
	this.hasConnection = false;

  //server sets this tadpole an id
  //TODO should handle new other tadpoles or don't recieve welcome for others
	this.welcome = function(user, users) {
		this.hasConnection = true;
    if (!model.tadpoles[-1]) {
      //new tadpole came
			model.tadpoles[user.id] = new Tadpole();
			model.arrows[user.id] = new Arrow(model.tadpoles[user.id], model.camera);
    }
    else {		
      //this tadpole is set
      model.userTadpole.id = user.id;
      model.userTadpole.name = user.name;
      model.tadpoles[user.id] = model.tadpoles[-1];
      delete model.tadpoles[-1];
      users.forEach(function(user) { 
        var tp = new Tadpole();
        //TODO move to Tadpole constructor
        tp.name = user.name;
        tp.targetX = user.x;
        tp.targetY = user.y;
        tp.color = user.color;
        tp.angle = user.angle;
        model.tadpoles[user.id] = tp;
        model.arrows[user.id] = new Arrow(model.tadpoles[user.id], model.camera);
      });
      
      $('#chat').initChat();
    }
	};
	
  //update for tadpole with specified id from server
	this.update = function(user) {
    var tp = model.tadpoles[user.id];
    tp.name = user.name;
    //skip updating self position
    if (model.userTadpole.id != user.id) {
      tp.targetX = user.x;
      tp.targetY = user.y;
      tp.color = user.color;
      tp.angle = user.angle;
      tp.momentum = user.momentum;
      tp.timeSinceLastServerUpdate = 0;
    }
	}
	
  //tadpole with id said a message
	this.message = function(msg) {
		var tadpole = model.tadpoles[msg.user_id];
		if(!tadpole) {
			return;
		}
		tadpole.timeSinceLastServerUpdate = 0;
		tadpole.messages.push(new Message(msg.text));
	}
	
  //log in on server performed
	this.signIn = function(data) {
	  model.authorized = !!data.authorized
	  if(!!data.username) {
	    model.username = data.username;
	    model.userTadpole.name = data.username;
	  }
	  
	  if(model.authorized) {
	    app.display_sign_in_success();
	  } else {
	    app.display_sign_in_failure();
	  }
	}

  //logout on server performed
	this.signOut = function(data) {
	  if(model.user) {
	    //data.errors
	  }
	}

  //sign up on server performed
	this.signUp = function(data) {
	  model.authorized = !!data.authorized
	  if(!!data.profile_errors) {
	    model.profile_errors = data.profile_errors
	  }
	  
	  if(model.authorized) {
	    model.userTadpole.name = data.username;
	    app.display_sign_up_success();
	  } else {
	    app.display_sign_up_failure();
	  }
	}

  //tadpole with specified id parted
	this.parted = function(id) {
		if(model.tadpoles[id]) {
			delete model.tadpoles[id];
			delete model.arrows[id];
		}
	}

  //closed connection by server
	this.connectionClosed = function() {
		this.hasConnection = false;
		$('#cant-connect').fadeIn(300);
	};
	
}

