angular.module('starter.controllers', [])

.controller('DashCtrl', function($scope) {})

.controller('ChatsCtrl', function($scope, Chats) {
  // With the new view caching in Ionic, Controllers are only called
  // when they are recreated or on app start, instead of every page change.
  // To listen for when this page is active (for example, to refresh data),
  // listen for the $ionicView.enter event:
  //
  //$scope.$on('$ionicView.enter', function(e) {
  //});

  $scope.chats = Chats.all();
  $scope.remove = function(chat) {
    Chats.remove(chat);
  };
})

.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
  $scope.chat = Chats.get($stateParams.chatId);
})

.controller('AccountCtrl', function($scope,$resource,$state,Task) {
  $scope.time = new Date();
  var task = $resource('http://192.168.1.64:8000/task/:id/');
  task.get(function (res) {
    $scope.taskList = res;
  }, function (err) {
    alert(JSON.stringify(err));
    $scope.taskList = [{
      id:1,title:'任务',description:'123456',created:new Date(),is_completed:false
    }]
  })
  $scope.toAdd = function () {
    $state.go('tab.task-detail',{
      id:0   //增加页面时候，浏览器中最后的参数值
    })
  }
  $scope.toDetail = function (item) {
    Task.detail = _.clone(item);
    $state.go('tab.task-detail',{
      id:item.id
    })
  }
  $scope.doRefresh = function () {
    getData();
  }
  function getData() {
    Task.getTask.get(function (res) {
      $scope.taskList = res;
    }, function (err) {
      alert(JSON.stringify(err));
    }).$promise.finally(function () {
      $scope.$broadcast('scroll.refreshComplete');
    });
  }
})

.controller('TaskDetailCtrl',function ($scope,$stateParams,$ionicHistory,$resource,Task) {
  var id = $stateParams.id;
  var isNew = id == 0 ? true : false;
  $scope.data = isNew ? {
    title:null,
    description:null
  } : _.clone(Task.detail);
  var task = $resource('http://192.168.1.64:8000/task/:id/');
  $scope.addTask = function () {
    console.log($scope.data);
    if (isNew) {
   task.save($scope.data,function () {
        $ionicHistory.goBack();
      })
    } else {
      Task.getTask.get($scope.data,function () {
        $ionicHistory.goBack();
      })
    }
  };

  $scope.deleteTask = function () {
    Task.getTask.delete({id:id},function(){
      $ionicHistory.goBack();
    })
  }
  $scope.comleted =function () {
    if(!$scope.data.is_completed) $scope.data.is_completed = !$scope.data.is_completed;
  }
});
