angular.module('avalanche3mobile.ActivityCtrl', [])
  .controller('MissionActivityCtrl', function($scope, $rootScope, $stateParams, OAuthService, DataService, RealtimeService, $state) {

    // Refresh Activities from server

    DataService.get('/missions/' + $state.params.missionId + "/activities", "", OAuthService.getToken())

    $rootScope.$on('$stateChangeSuccess',
      function(event, toState, toParams, fromState, fromParams){
        DataService.get('/missions/' + $state.params.missionId + "/activities", "", OAuthService.getToken())
    });

    $rootScope.$on('get-data-success:/missions/' + $state.params.missionId + '/activities', function() {
      if(!$scope.$$phase) {
        $scope.$apply(function(){
          $scope.mission.activities = DataService.getResponse().data;
        });
      } else {
        $scope.mission.activities = DataService.getResponse().data;
      }
    });

    // Start Realtime subscription to new activities

    RealtimeService.subscribe('/missions/' + $state.params.missionId, function(activity) {
      $scope.$apply(function() {
        $scope.mission.activities.push(activity);
        console.log(activity);
      });
    });

    // Send message

    $scope.message = "";
    $scope.sendMessage = function() {
      DataService.post('/missions/' + $state.params.missionId + "/messages", {content : $scope.message }, OAuthService.getToken())
      $scope.message = "";
    }

    // Misc

    $scope.activityIconClass = function(activity){
      if(activity.trackable_type == "Message" || activity.trackable_type == "Task") {
        return "item-avatar";
      } else {
        return "item-icon-left";
      }
    }
  })
