 ## Attachment Directive
 #############################################################################
 
-AttachmentDirective = ($log) ->
+AttachmentDirective = ($log, $repo, $rs, $confirm) ->
     singleAttachment = _.template("""
     <div class="attachment-name">
         <span class="icon.icon-document"></span>

    """) # TODO: i18n

    link = ($scope, $el, $attrs, $model) ->
        render = (attachment, isEditable=false) ->
            ctx = {
                id: attachment.id

        attachment = $scope.$eval($attrs.tgAttachment)
        render(attachment)

        ## Actions (on view mode)
        $el.on "click", "a.settings.icon-edit", (event) ->
            event.preventDefault()
            render(attachment, true)

        $el.on "click", "a.settings.icon-delete", (event) ->
            event.preventDefault()

            title = "Delete attachment" # i18n
            subtitle = "the attachment '#{attachment.name}'"

            onSuccess = ->
                $ctrl.loadAttachments(attachment.object_id)
                $confirm.notify("success", null, "We've deleted #{subtitle}.") #TODO: i18in

            onError = ->
                $confirm.notify("error", null, "We have not been able to delete #{subtitle}.") #TODO: i18in

            $confirm.ask(title, subtitle).then ->
                $repo.remove(attachment).then(onSuccess, onError)

        ## Actions (on edit mode)
        $el.on "click", "a.editable.icon-delete", (event) ->
            event.preventDefault()
            render(attachment)

        $el.on "click", "a.editable.icon-floppy", (event) ->
            newDescription = $el.find("input[name='description']").val()
            newIsDeprecated = $el.find("input[name='is-deprecated']").prop("checked")

            if newDescription != attachment.description
                attachment.setAttr("description", newDescription)
            if newIsDeprecated != attachment.is_deprecated
                attachment.setAttr("is_deprecated", newIsDeprecated)

            onSuccess = ->
                $ctrl.loadAttachments(attachment.object_id)
                $confirm.notify("success")

            onError = ->
                $confirm.notify("error")

            if attachment.isModified()
                $repo.save(attachment).then(onSuccess, onError)

        ## On destroy
        $scope.$on "$destroy", ->
            $el.off()
