#!/usr/bin/env python3
#
# Simple script to export a file from the datastore
# Reinier Heeres, <reinier@heeres.eu>, 2007-12-24
# Phil Bordelon <phil@thenexusproject.org>

import os
import shutil
import argparse
from dbus import DBusException

from sugar3.datastore import datastore
import sugar3.mime

from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)

# Limit the number of objects returned on an ambiguous query to this number,
# for quicker operation.
RETURN_LIMIT = 2


def build_argument_parser():

    usage = "%(prog)s [-o OBJECT_ID] [-q SEARCH_STR] [-m] OUTFILE"
    parser = argparse.ArgumentParser(usage=usage)

    parser.add_argument('outfile',
                        help="Name the output file with the explicit name",
                        metavar="OUTFILE")
    parser.add_argument("-o", "--object_id", action="store", dest="object_id",
                        help="Retrieve object with explicit ID OBJECT_ID",
                        metavar="OBJECT_ID", default=None)

    parser.add_argument("-q", "--query", action="store", dest="query",
                        help="Full-text-search the metadata for SEARCH_STR",
                        metavar="SEARCH_STR", default=None)

    parser.add_argument("-m", "--metadata", action="store_true",
                        dest="show_meta",
                        help="Show all non-preview metadata [default: hide]",
                        default=False)

    return parser


if __name__ == "__main__":

    argument_parser = build_argument_parser()
    args = argument_parser.parse_args()
    if not args.outfile:
        argument_parser.print_help()
        exit(0)

    try:
        dsentry = None

        # Get object directly if we were given an explicit object ID.
        if args.object_id is not None:
            dsentry = datastore.get(args.object_id)

        # Compose the query based on the options provided.
        if dsentry is None:
            query = {}

            if args.query is not None:
                query['query'] = args.query

            # We only want a single file at a time; limit the number of objects
            # returned to two, as anything more than one means the criteria
            # were not limited enough.
            objects, count = \
                datastore.find(query, limit=RETURN_LIMIT, sorting='-mtime')
            if count > 1:
                print(
                    'WARNING: %d objects found; getting most recent.' %
                    count)
                for i in range(1, RETURN_LIMIT):
                    objects[i].destroy()

            if count > 0:
                dsentry = objects[0]

        # If neither an explicit object ID nor a query gave us data, fail.
        if dsentry is None:
            print('ERROR: unable to determine journal object to copy.')
            argument_parser.print_help()
            exit(0)

        # Print metadata if that is what the user asked for.
        if args.show_meta:
            print('Metadata:')
            for key, val in dsentry.metadata.get_dictionary().items():
                if key != 'preview':
                    print('%20s -> %s' % (key, val))

        # If no file is associated with this object, we can't save it out.
        if dsentry.get_file_path() == "":
            print('ERROR: no file associated with object, just metadata.')
            dsentry.destroy()
            exit(0)

        outname = args.outfile
        outroot, outext = os.path.splitext(outname)

        # Do our best to determine the output file extension, based on Sugar's
        # MIME-type-to-extension mappings.
        if outext == "":
            mimetype = dsentry.metadata['mime_type']
            outext = sugar3.mime.get_primary_extension(mimetype)
            if outext is None:
                outext = "dsobject"
            outext = '.' + outext

        # Lastly, actually copy the file out of the datastore and onto the
        # filesystem.
        shutil.copyfile(dsentry.get_file_path(), outroot + outext)
        print('%s -> %s' % (dsentry.get_file_path(), outroot + outext))

        # Cleanup.
        dsentry.destroy()

    except DBusException:
        print('ERROR: Unable to connect to the datastore.\n'
              'Check that you are running in the same environment as the '
              'datastore service.')

    except Exception as e:
        print('ERROR: %s' % (e))
