#!/usr/bin/env python3
#
# Simple script to import a file to the datastore
# Reinier Heeres, <reinier@heeres.eu>, 2007-12-20
#
# Modified by Phil Bordelon <phil@thenexusproject.org> 2007-12-20, 2007-12-21
# to support adding metadata.  Note that the MIME-type is required,
# as otherwise the datastore will not accept the file.

import os
import argparse
from gettext import gettext as _
from dbus import DBusException

from sugar3.datastore import datastore
from sugar3 import mime

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


def build_option_parser():

    usage = "%(prog)s <file> [-m MIMETYPE] [-t TITLE] [-d DESC] " \
            "[-T tag1 [-T tag2 ...]]"
    parser = argparse.ArgumentParser(usage=usage)

    parser.add_argument("file", help="File to be copied to journal")
    parser.add_argument("-t", "--title", action="store", dest="title",
                        help="Set the title of the journal entry",
                        metavar="TITLE", default=None)
    parser.add_argument("-d", "--description", action="store",
                        dest="description", metavar="DESC",
                        help="Set the description of the journal entry",
                        default=None)
    parser.add_argument("-m", "--mimetype", action="store",
                        dest="mimetype", metavar="MIMETYPE",
                        help="Set the file's MIME-type", default=None)
    parser.add_argument("-T", "--tag", action="append", dest="tag_list",
                        help="Add tag TAG to the journal entry's tags; "
                             "this option can be repeated",
                        metavar="TAG")
    return parser


if __name__ == "__main__":

    argument_parser = build_option_parser()
    args = argument_parser.parse_args()
    if not args.file:
        argument_parser.print_help()
        exit(0)

    fname = args.file
    absname = os.path.abspath(fname)
    if not os.path.exists(absname):
        print('Error: File does not exist.')
        argument_parser.print_help()
        exit(0)

    try:
        entry = datastore.create()
        entry.set_file_path(absname)

        # Set the mimetype to the provided one.
        if args.mimetype is None:
            entry.metadata['mime_type'] = mime.get_for_file(absname)
        else:
            entry.metadata['mime_type'] = args.mimetype

        # If no title is given, use the filename.
        if args.title:
            entry.metadata['title'] = args.title
        else:
            entry.metadata['title'] = os.path.basename(fname)

        # Use the description given, otherwise leave it blank.
        if args.description:
            entry.metadata['description'] = args.description
        else:
            entry.metadata['description'] = _('From: %s') % fname

        # Lastly, if any tags are given, combine them into a single string
        # and save them.
        if args.tag_list:
            tag_string = " ".join(args.tag_list)
            entry.metadata['tags'] = tag_string

        datastore.write(entry)
        print('Created as %s' % (entry.object_id))

        entry.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))
