#!/usr/bin/env python
# encoding: utf-8
"""
Generate file listings from test_images_good.

Authors:
 * Chris Allan <callan at lifesci dot dundee dot ac dot uk>
 * Will Moore <will at lifesci dot dundee dot ac dot uk>
 * Brian Loranger <brian dot loranger at lifesci dot dundee dot ac dot uk>
"""

#  
#  Copyright (c) 2010 University of Dundee. All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions
#  are met:
#  1. Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#  2. Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
#  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
#  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
#  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
#  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
#  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
#  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
#  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
#  SUCH DAMAGE.


import sys
import os
import re

from getopt import getopt, GetoptError
from fnmatch import fnmatch

EXTENSIONS = {
    "al3d": { "glob": ["*.al3d"] },
    "amira": { "glob": ["*.am"] },
    "analyze": { "glob": ["*.hdr"] },
    "andor": { "glob": ["*.tif"] },
    "ariol": { "glob": ["*.jpg"] },
    "avi": { "glob": ["*.avi"] },
    "bd_pathway": { "glob": ["*.exp"] },
    "bigtiff": { "glob": ["*.tif"] },
    "bio-rad_pic": { "glob": ["*.pic"] },
    "bio-rad_raw": { "glob": ["*.xml"] },
    "bmp": { "glob": ["*.bmp"] },
    "cellomics": { "glob": ["*.c01"] },
    "dicom": { "glob": ["*.dcm"] },
    "dv": { "glob": ["*.dv"] },
    "dv_single": { "glob": ["*.dv"] },
    "al3d": { "glob": ["*.al3d"] },
    "eps": { "glob": ["*.eps"] },
    "fei": { "glob": ["*.img"] },
    "fits": {"glob": ["*.fits"] },
    "flex": {"glob": ["*.mea"] },
    "ics": {"glob": ["*.ics"] },
    "fluoview": {"glob": ["*.tif"] },
    "fv1000": {"glob": ["*.oib"] },
    "gatan": {"glob": ["*.dm3"] },
    "gel": {"glob": ["*.gel"] },
    "gif": {"glob": ["*.gif"] },
    "ics": {"glob": ["*.ics"] },
    "imacom": {"glob": ["*.fff"] },
    "imagepro": {"glob": ["*.tif"] },
    "improvision": {"glob": ["*.tif"] },
    "ims": {"glob": ["*.ims"] },
    "ims_large": {"glob": ["*.ims"] },
    "ipl": {"glob": ["*.ipl"] },
    "ivision": {"glob": ["*.ipm"] },
    "jpeg2000": {"glob": ["*.jp2"] },
    "jpg": {"glob": ["*.jpg"] },
    "khoros": {"glob": ["*.xv"] },
    "l2d": {"glob": ["*.l2d"] },
    "lei": {"glob": ["*.lei"] },
    "lei_martin_sp2": {"glob": ["*.lei"] },
    "leica-tcs": {"glob": ["*.tif"] },
    "li-flim": {"glob": ["*.fli"] },
    "lif": {"glob": ["*.lif"] },
    "lif_martin": {"glob": ["*.lif"] },
    "liff": {"glob": ["*.liff"] },
    "lsm": {"glob": ["*.lsm"] },
    "lsm_martin": {"glob": ["*.lsm"] },
    "micromanager": {"glob": ["*.txt"] },
    "micromanager_2": {"glob": ["*.txt"] },
    "minc": {"glob": ["*.mnc"] },
    "mng": {"glob": ["*.mng"] },
    "mrc": {"glob": ["*.mrc"] },
    "multi_ome-tif": {"glob": ["*.tif"] },
    "naf": {"glob": ["*.naf"] },
    "nd2": {"glob": ["*.nd2"] },
    "nifti": {"glob": ["*.hdr"] },
    "nikon-jp2": {"glob": ["*.jp2"] },
    "nrrd": {"glob": ["*.pic", "*.pic.gz", "*.pic.gz.nhdr", "*.pic.nhdr"] },
    "oif": {"glob": ["*.oif"] },
    "ome-tiff": {"glob": ["*.tif"] },
    "pct": {"glob": ["*.pct"] },
    "pcx": {"glob": ["*.pcx"] },
    "png": {"glob": ["*.png"] },
    "prairie": {"glob": ["*.xml"] },
    "psd": {"glob": ["*.psd"] },
    "quicktime": {"glob": ["*.mov"] },
    "raw": {"glob": ["*.raw"] },
    "sdt": {"glob": ["*.sdt"] },
    "simplepci": {"glob": ["*.cxd"] },
    "slidebook": {"glob": ["*.sld"] },
    "stk": {"glob": ["*.stk"] },
    "svs": {"glob": ["*.svs"], "groups": ["big-image"]},
    "targa": {"glob": ["*.tga"] },
    "tif": {"glob": ["*.tif", "*.tiff"] },
    "tillvision": {"glob": ["*.vws"] },
    "visitech": {"glob": ["*.html"] },
    "zvi": {"glob": ["*.zvi"] },
}

def usage(error):
    """Prints usage so that we don't have to. :)"""
    cmd = sys.argv[0]
    print """%(error)s
Usage: %(cmd)s <source>
Creates a file listing from the test_images_good extension listing.

Options:
  -g        Groups to filter from the listing

Examples:
  %(cmd)s $HOME/test_images_good

Report bugs to ome-devel@lists.openmicroscopy.org.uk""" % \
        {'error': error, 'cmd': cmd}
    sys.exit(2)

def has_group(details, filter_groups):
    try:
        for filter_group in filter_groups:
            if filter_group in details['groups']:
                return True
    except KeyError:
        pass
    return False

def build_files_txt(source, filter_groups):
    files_txt = list()
    for subdir, details in EXTENSIONS.items():
        subdir = os.path.join(source, subdir)
        if not os.path.exists(subdir):
            print "WARNING: %s does not exist!" % subdir
            continue
        if has_group(details, filter_groups):
            continue
        subdir_files_txt = list()
        for root, dirs, files in os.walk(subdir):
            for name in files:
                for glob in details['glob']:
                    if fnmatch(name.lower(), ".*"):
                        continue
                    if fnmatch(name.lower(), glob):
                        subdir_files_txt.append(os.path.join(root, name))
        if len(subdir_files_txt) == 0:
            print "WARNING: %s %r matched nothing!" % (subdir, details)
        files_txt += subdir_files_txt
    return files_txt

if __name__ == "__main__":
    try:
        options, args = getopt(sys.argv[1:], "g:", [])
    except GetoptError, (msg, opt):
        usage(msg)

    filter_groups = list()
    for option, argument in options:
        if option == "-g":
            filter_groups.append(argument)

    try:
        source, = args
    except ValueError:
        usage("Must specify a source directory!")
    files_txt = build_files_txt(source, filter_groups)
    for entry in files_txt:
        print entry
