#!/usr/bin/python
from l3tlib.command import L3tBugCommand

DEFAULT_TYPE = "application/octet-stream"


class Attach(L3tBugCommand):

    _temporary_file = None

    descr = """\
Attaches a file to a given bug
"""
    usage = "%prog [-b BUG | BUG | -i INCIDENT]  -f FILE <options>"

    def init_parser(self, parser):
        super(Attach, self).init_parser(parser)
        parser.add_option("--description", default=None,
                          help="Set the attachment description")
        parser.add_option("-m", "--message", dest="comment", default=None,
                          help=("Comment to add on the bug (besides the "
                                "attachment description)"))
        parser.add_option("-t", "--type",
                          default=DEFAULT_TYPE,
                          help=("File content type (default %s)" %
                                (DEFAULT_TYPE)))
        parser.add_option("--patch", default=False, action="store_true",
                          help="The attachment is a patch")
        parser.add_option("--text", default=False, action="store_true",
                          help="The attachment is a text file")
        parser.add_option("--file", default=None,
                          help="File to attach")
        parser.add_option("-p", "--private", default=False,
                          action="store_true",
                          help="Make the attachment and comment private")

    def parse_args(self, parser, values):
        opts, args = super(Attach, self).parse_args(parser, values)
        if not opts.file:
            parser.error("--file/-f is required")
        return opts, args

    def run(self):
        bug = self.l3t.get_bug(self.opts.incident, self.opts.bug)
        if self.opts.text:
            self.opts.type = "text/plain"
        self.l3t.add_attachment(bug.bug_id, self.opts.file, self.opts.type,
                                description=self.opts.description,
                                is_patch=self.opts.patch,
                                is_private=self.opts.private,
                                comment=self.opts.comment)


Attach().main()
