#! /usr/bin/env python

#
#  equerybts  --  Bugzilla query tool from command line
#
#   Copyright (c) 2004 Akinori Hattori, All rights reserved.
#
#   Permission is hereby granted, free of charge, to any person obtaining a
#   copy of this software and associated documentation files (the "Software"),
#   to deal in the Software without restriction, including without limitation
#   the rights to use, copy, modify, merge, publish, distribute, sublicense,
#   and/or sell copies of the Software, and to permit persons to whom
#   the Software is furnished to do so, subject to the following conditions:
#
#   The above copyright notice and this permission notice shall be included in
#   all copies or substantial portions of the Software.
#
#   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
#   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
#   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
#   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
#   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
#   OTHER DEALINGS IN THE SOFTWARE.
#
#  $Id: equerybts 81 2004-03-01 13:44:18Z hattya $
#

import errno
import getopt
import sys

sys.path.insert(1, './lib')

import equerybts.ui as eui
import equerybts.termctl as etermctl
import equerybts.textproc as etextproc
import equerybts.exceptions as eexcept


__program__ = 'equerybts'
__version__ = '0.0 (r85)'


def main():
    query_from = query_seed = ''
    mprompt = eui.Prompt(__program__, __version__)

    options, values = getopt.getopt(sys.argv[1:],
                                    'h',
                                    ['help', 'version'])

    if options:
        for opt, val in options:
            if opt in ['-h', '--help']:
                print 'usage: %s [option] ...' % __program__
                print
                print 'options:'
                print
                print '  --version         show program version.'
                print '  -h, --help        show this message.'
                print

            elif opt in ['--version']:
                print '%s, version %s' % (__program__, __version__)
                print

        sys.exit(0)


    if not values:
        raise eexcept.EQueryBTSArgumentError, (errno.EINVAL, 'invalid argument.')

    elif len(values) == 1 and values[0].isdigit():
        query_from = 'number'
        query_seed = values[0]

    else:
        query_from = 'string'
        query_seed = [x for x in values]


    if query_from == 'number':
        mprompt.query_number(query_seed)
        mprompt.main()

    elif query_from == 'string':
        mprompt.query_string(query_seed)
        mprompt.main()

def error_output(*text):
    mtermctl = etermctl.FancyText()
    mtextproc = etextproc.TextProc()

    text = mtextproc.join_aa_list(text)

    print
    print mtermctl.blue('Error:', text)
    print


if __name__ == '__main__':
    try:
        main()

    except KeyboardInterrupt:
        print

    except eexcept.EQueryBTSArgumentError, e:
        error_output(e.msg)

    except eexcept.NoPager, e:
        error_output('please set $PAGER.')

    except eexcept.URLOpenError, e:
        error_output('http error.')

    except eexcept.BugParserError, e:
        error_output(e.msg, 'caused an error.')

    except eexcept.BugNotFound, e:
        error_output('bug not found.')

    except eexcept.SaveAttachmentError, e:
        error_output(e.args[1], ':', e.filename)

    except eexcept.UnknownError, e:
        if not e.errno:
            error_output(e.msg)

    except getopt.GetoptError, e:
        pass
