#!/usr/bin/env python

# pybm-match :  Bookmark matching
# Copyright 2008, 2009 Bart Spaans
#
# TODO:
#    configuration flag: pybm-match -c ~/.bm-match [FILES]
#    matching on username, permissions, height and width (?)
#    defining new rule-aliases for expressions
#    parameter expansion in expressions

import os
import sys
import btools.common as common
from btools.matching.FileMatcher import FileMatcher


name = "bm-match"
description = "Weighted bookmark matching"
commands = [ (["-h", "--help"], "", 
            "This help screen."),
            (["-i", "--inspect"], "FILE", 
            "Outputs weighted table of matching destination bookmarks."),
            (["-n", "--new"], "",
            "Initialize new config file from template."),
            (["-nf", "--force-new"], "",
            "Same as -n, but overwrites file if it already exists."),
            ]
usage = [("COMMAND [ARGUMENTS]", "Execute command"),
         ("[FILES]", "Match FILES")]
examples = [("-nf", "Force a new empty configuration file in the current directory"),
            ("test.txt", "Match and move test.txt using the rules in .bm-match")]


def get_FileSorter():
    return FileMatcher()


def output_weighted_tabled(table):
    if table == []:
        return
    width = max(map(lambda a: len(a[0]), table))
    for bookmark, weight in table:
        print ("%" + str(width) + "s    %.4f") % (bookmark, weight)




def cli_inspect_file(args):
    if args == []:
        return
    fs = get_FileSorter()
    output_weighted_tabled(fs.get_weighted_table(args[0]))

def cli_new_config_file(forcenew = False):
    if os.path.exists(".bm-match"):
        if not forcenew:
            print "Error: .bm-match already exists in this directory. Use -nf to force a new file."
            return

    f = open(common.template, "r")
    tmp = f.read()
    f.close()

    f = open(".bm-match", "w")
    f.write(tmp)
    f.close()
    print ".bm-match written succesfully."


def cli_output_help(args):
    common.cli_module_help(globals())


def cli_match(args):
    f = get_FileSorter()
    map(f.match, args)



def command_line_interface():
    if len(sys.argv) == 1:
        return cli_output_help(sys.argv)
    command = str.lower(sys.argv[1])
    args = sys.argv[2:]

    if command in ["-i", "--inspect"]:
        cli_inspect_file(args)
    elif command in ["-h", "--help"]:
        cli_output_help(sys.argv)
    elif command in ["-n", "--new"]:
        cli_new_config_file()
    elif command in ["-nf", "--force-new"]:
        cli_new_config_file(True)
    else:
        cli_match(sys.argv[1:])


if __name__ == '__main__':
    command_line_interface()
