#!/usr/bin/env python

# pybm-match :  Bookmark matching
# Copyright 2008, 2009 Bart Spaans
#
# TODO:
#    configuration flag: bm-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 = [(["-a", "--ask"], "FILES", "Ask if the match is right"),
            (["-e", "--edit"], "", "Edit the configuration file with the default editor"),
            (["-h", "--help"], "", 
            "This help screen."),
            (["-i", "--inspect"], "FILES", 
            "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")]

long_description="""bm-match reads rules from a configuration file (named .bm-match)
to be able to categorize files based on a number of heuristics.
"""

common.loglevel = 2

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 inspect(fs, file):
    if os.path.isdir(file):
        map(lambda a: inspect(fs, os.path.join(file, a)), os.listdir(file))
    else:
        print "===", file, "==="
        output_weighted_tabled(fs.get_weighted_table(file))

def cli_edit(args):
    file = common.get_conf_location()
    common.edit_file(file)

def cli_inspect_file(args):
    if args == []:
        return
    map(lambda a: inspect(get_FileSorter(), a), args)

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."
    common.edit_file(".bm-match")


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


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

def cli_ask(args):
    f = get_FileSorter()
    f.interactive = True
    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 ["-a", "--ask"]:
        cli_ask(args)
    elif command in ["-e", "--edit"]:
        cli_edit(args)
    elif 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()
