lunchControllers = angular.module 'lunchControllers'

lunchControllers.controller 'UpdateOrderCtrl', ['$scope','socket','$routeParams','$location','$sce',
    UpdateOrderController = ($scope, socket, $routeParams, $location, $sce) ->
        $scope.show = false
        $scope.showMenuUrl = false
        $scope.invitees = []
        $scope.menuUrl = ''

        socket.get '/invitee/findOne', id: $routeParams['inviteeId'], (inviteeResponse) ->
            $scope.invitee = inviteeResponse

            socket.get '/run/' + inviteeResponse.run_id,
                (runResponse) ->
                    $scope.show = true
                    $scope.showMenuUrl = runResponse.menuUrl
                    $scope.menuUrl = $sce.trustAsResourceUrl(runResponse.menuUrl)
                    $scope.run = runResponse
                    $scope.$apply()

            socket.get '/invitee/find', run_id: inviteeResponse.run_id, (allResponse) ->
                $scope.invitees = allResponse
                $scope.$apply()

        socket.on 'message', (m) ->
            if m.verb is 'update' and m.data.run_id is $scope.run.id
                invitee = _.findWhere $scope.invitees, run_id: m.data.run_id
                _.extend invitee, m.data
                $scope.$apply()

        $scope.submit = (invitee) ->
            socket.put '/invitee/' + $routeParams['inviteeId'], { order: invitee.order }, (response) ->
                $location.path '/run/' + $scope.run.id
                $scope.$apply()
]
