#!/usr/bin/python
# -*- coding: utf-8 -*-
### BEGIN LICENSE
# Copyright (C) 2010-2013 Emilien Klein <emilien _AT_ klein _DOT_ st>
# 
# This program is free software: you can redistribute it and/or modify it 
# under the terms of the GNU General Public License version 3, as published 
# by the Free Software Foundation.
# 
# This program is distributed in the hope that it will be useful, but 
# WITHOUT ANY WARRANTY; without even the implied warranties of 
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR 
# PURPOSE.  See the GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License along 
# with this program.  If not, see <http://www.gnu.org/licenses/>.
### END LICENSE

import sys
import os
from gi.repository import Gtk

import gettext
from gettext import gettext as _
from gettext import ngettext
gettext.textdomain('nautilus-image-manipulator')

# Add project root directory (enable symlink, and trunk execution).
PROJECT_ROOT_DIRECTORY = os.path.abspath(
    os.path.dirname(os.path.dirname(os.path.realpath(sys.argv[0]))))

if (os.path.exists(os.path.join(PROJECT_ROOT_DIRECTORY, 'nautilus_image_manipulator'))
    and PROJECT_ROOT_DIRECTORY not in sys.path):
    sys.path.insert(0, PROJECT_ROOT_DIRECTORY)
    os.putenv('PYTHONPATH', PROJECT_ROOT_DIRECTORY) # for subprocesses

from nautilus_image_manipulator import NautilusImageManipulatorDialog
from nautilus_image_manipulator.helpers import get_builder

if __name__ == "__main__":
    # Support for command line options.
    import logging
    import optparse
    parser = optparse.OptionParser(version="%prog 1.3")
    parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help=_("show debug messages").decode('utf-8'))
    parser.add_option("-f", "--file", action="append", dest="files", help=_("a file to be resized. Use multiple arguments to resize multiple files.").decode('utf-8'), metavar="FILE")
    (options, args) = parser.parse_args()

    # Set the logging level appropriately.
    logging_level = logging.DEBUG if options.verbose else logging.INFO
    logging.basicConfig(level=logging_level)
    # Force the logging level. Used in case logging was already initialized,
    # for instance when ImageManipulations failed to import GExiv2.
    logging.root.setLevel(logging_level)
    logging.log(logging_level, "Logging set to level %s" %
                           logging.getLevelName(logging_level))

    images = []
    if options.files:
        # Filter the invalid filenames out
        for f in options.files:
            if os.path.exists(f):
                images.append(f)
            else:
                logging.info("File '%s' does not exist" % f)

    if not images:
        optionName = ngettext("_Resize image", "_Resize images", 1)
        # Display an error message since we don't have images to work on
        label = Gtk.Label(label=_('Nautilus Image Manipulator needs to be provided with a list of images to resize.\nPlease right-click on an image and select the "%(resizeImages)s" option.') % {"resizeImages": optionName.replace("_", "")})
        label.set_padding(10, 5)
        dialog = Gtk.Dialog(_("No images provided"),
                           None,
                           Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
                           (Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT))
        dialog.vbox.pack_start(label, True, True, 0)
        label.show()
        response = dialog.run()
        dialog.destroy()
    else:
        # Run the application.
        dialog = NautilusImageManipulatorDialog.NautilusImageManipulatorDialog()
        dialog.set_files(images)
        dialog.show()
        try: Gtk.main()
        except KeyboardInterrupt: pass
