#!/usr/bin/python

# tzdir.py
#       --copyright--                   Copyright 2007 (C) Tranzoa, Co. All rights reserved.    Warranty: You're free and on your own here. This code is not necessarily up-to-date or of public quality.
#       --url--                         http://www.tranzoa.net/tzpython/
#       --email--                       pycode is the name to send to. tranzoa.com is the place to send to.
#       --bodstamps--
#       December 20, 2005       bar
#       November 18, 2007       bar     turn on doxygen
#       November 27, 2007       bar     insert boilerplate copyright
#       May 17, 2008            bar     email adr
#       September 26, 2010      bar
#       May 12, 2011            bar     some unicode/utf8 things
#                                       -q doesn't do anything except be compatable with tzdir.c
#                                       don't be confused by brackets in the directory names (glob uses fnmatch, which uses brackets - we just use fnmatch for the base file names)
#       November 29, 2011       bar     pyflake cleanup
#       May 27, 2012            bar     doxygen namespace
#       --eodstamps--
##      \file
#       \namespace              tzpython.tzdir
#
#
#       Print a directory with the Unix decimal time for files
#
#

import  fnmatch
import  os
import  sys

import  TZCommandLineAtFile
import  tzlib



def strip_shared_dirs(fns) :
    """
        Do what os.path.commonprefix should be used for.
    """

    if  len(fns) == 1 :
        hfns    = [ os.path.basename(fn) for fn in fns ]
    else        :
        cdnam   = os.path.commonprefix([ os.path.dirname(fn) for fn in fns ])
        ln      = len(cdnam)
        dn      = fns[0]
        while len(dn) > ln :
            ndn = os.path.dirname(dn)
            if  len(ndn) == len(dn) :
                break
            dn  = ndn
        if  dn == os.path.dirname(fns[0]) :
            fns = [ os.path.basename(fn) for fn in fns ]
            ln  = 0
            prc = ""
        elif os.path.dirname(dn) != dn :
            ln  = len(dn)
            prc = "..."
        else    :
            ln  = 0
            prc = ""
        hfns    = [ prc + fn[ln:] for fn in fns ]

    return(hfns)


if  False :
    fns = [ "C:1234/567/89.01", "C:1234/567/89.0x", ]
    print strip_shared_dirs(fns)

    fns = [ "C:\\1234/5x7/89.01", "C:\\1234/567/89.01", ]
    print strip_shared_dirs(fns)

    fns = [ "C:\\x234/5x7/89.01", "C:\\1234/567/89.01", ]
    print strip_shared_dirs(fns)



def fmt_mtime(fname) :
    try     :
        return("%10u" % os.path.getmtime(fname))
    except os.error :
        pass

    return("")


def fmt_name(fname) :
    return(fname.encode('utf8'))



class a_thang :


    def _parse_cmd_line(me) :
        """
            Parse command line parameters
        """


        def __cmd_line_help() :
            print """

I print out a directory listing.

Tell me an (ambiguous) file name or a directory name.

Options:

  --subdirs or  -s      Do sub-directories.
            """

            pass



        del sys.argv[0]

        TZCommandLineAtFile.expand_at_sign_command_line_files(sys.argv)


        while True :
            oi  = tzlib.array_find(sys.argv, [ "--help", "-h", "-?", "/?", "/H", ] )
            if  oi < 0 :    break
            del sys.argv[oi]
            __cmd_line_help()
            sys.exit(101)

        while True :
            oi  = tzlib.array_find(sys.argv, [ "--subdirs", "-s", ] )
            if  oi < 0 :    break
            del sys.argv[oi]
            me.do_subdirs   = True

        while True :
            oi  = tzlib.array_find(sys.argv, [ "--quiet", "-q", ] )
            if  oi < 0 :    break
            del sys.argv[oi]
            me.quiet        = True

        pass


    def do_cmd_line_arg(me, argv) :
        a   = [ argv[0] ]

        if  tzlib.array_find(a, [ "--name", "-n", "/n", "/N", ]) >= 0 :
            if  me.unk_formats  :
                me.unk_formats  = False
                me.formats      = []
            me.formats.append(fmt_name)
            argv.pop(0)
            return(True)

        if  tzlib.array_find(a, [ "--unix", "-u", "/u", "/U", ]) >= 0 :
            if  me.unk_formats  :
                me.unk_formats  = False
                me.formats      = []
            me.formats.append(fmt_mtime)
            argv.pop(0)
            return(True)

        return(False)


    def __init__(me) :
        me.do_subdirs       =   False
        me.quiet            =   False
        me.unk_formats      =   True
        me.formats          =   [ fmt_mtime, fmt_name ]

        me.base_amb_name    =   ""

        me._parse_cmd_line()


    def print_dir_entry(me, fname) :
        s       = " ".join([ fmt(fname) for fmt in me.formats ])
        print s


    #   a_thang





def print_em(me, s) :
    ( dn, fn )  = os.path.split(s)
    fns = os.listdir(dn)
    fns = fnmatch.filter(fns, fn)                   # in practice, the basename is *.* or *. But in any case, we don't want to use the [] glob/fnmatch logic for dirs.
    for fname in fns :
        me.print_dir_entry(os.path.join(dn, fname))
    pass



def print_dir(me, s, names) :
    if  me.base_amb_name :
        print_em(me, os.path.abspath(os.path.join(s, me.base_amb_name)))
    else :
        print_em(me, os.path.abspath(os.path.join(s, u"*.*")))
    pass



#   Test code.
#
#
if __name__ == '__main__' :
    me = a_thang()

    while len(sys.argv) :
        if  not me.do_cmd_line_arg(sys.argv) :
            s   = sys.argv.pop(0).decode('utf8')

            if  s[0:1] == "-" :
                if  not me.quiet :
                    print   "Did you mean this to be a file or directory:", s
                pass

            if me.do_subdirs :
                if  not os.path.isdir(s) :
                    ( s, me.base_amb_name ) = os.path.split(os.path.normpath(s))
                    if  s == "" :   s = u"."
                    if  not os.path.isdir(s) :
                        print_dir(me, s, [] )
                    else :
                        os.path.walk(s, print_dir, me)
                    me.base_amb_name    =   ""
                else :
                    os.path.walk(s, print_dir, me)
                pass

            elif    not os.path.isdir(s) :
                print_em(me, s)

            else :
                print_dir(me, s, [])

            pass
        pass
    pass

#
#
#
# eof
