#! /usr/bin/python3
# -*- coding: utf-8 -*-

#    Copyright (c) 2012 David Calle <davidc@framli.eu>

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY 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/>.

import gettext
import locale
import sys
import os
from gi.repository import Dee, Unity, GLib, GObject, Gio

APP_NAME = "unity-lens-photos"
LOCAL_PATH = "/usr/share/locale/"

gettext.bindtextdomain(APP_NAME, LOCAL_PATH)
gettext.textdomain(APP_NAME)
_ = gettext.gettext

CAT_MINE = _("My Photos")
CAT_FRIENDS = _("Friends Photos")
CAT_ONLINE = _("Online Photos")
CAT_GLOBAL = _("Photos")
CAT_RECENT = _("Recent")
FILTER_DATE = _("Date")
FILTER_OPTION_7DAYS = _("Last 7 days")
FILTER_OPTION_30DAYS = _("Last 30 days")
FILTER_OPTION_6MONTHS = _("Last 6 months")
FILTER_OPTION_OLDER = _("Older")
SOURCES = _("Sources")
HINT = _("Search Photos")

BUS_NAME = "net.launchpad.lens.photos"
THEME = "/usr/share/icons/unity-icon-theme/places/svg/"

class Daemon:
    def __init__(self):
        self._lens = Unity.Lens.new ("/net/launchpad/lens/photos", "photos")
        self._lens.props.search_hint = HINT
        self._lens.props.visible = True
        self._lens.props.search_in_global = True
#        self._lens.props.home_lens_default_name = CAT_GLOBAL
        self._lens.props.sources_display_name = SOURCES
        m = Merger()
        mg = Merger()
        self._lens.props.merge_strategy = m
        self._lens.props.global_merge_strategy = mg
        
        # Populate categories
        cats = []
        cats.append (Unity.Category.new (CAT_RECENT,
                                         Gio.ThemedIcon.new(THEME + "group-recent.svg"),
                                         Unity.CategoryRenderer.VERTICAL_TILE))
        cats.append (Unity.Category.new (CAT_MINE,
                                         Gio.ThemedIcon.new(THEME + "group-photos.svg"),
                                         Unity.CategoryRenderer.VERTICAL_TILE))
        cats.append (Unity.Category.new (CAT_FRIENDS,
                                         Gio.ThemedIcon.new(THEME + "group-friends.svg"),
                                         Unity.CategoryRenderer.VERTICAL_TILE))
        cats.append (Unity.Category.new (CAT_ONLINE,
                                         Gio.ThemedIcon.new(THEME + "group-internet.svg"),
                                         Unity.CategoryRenderer.VERTICAL_TILE))
        cats.append (Unity.Category.new (CAT_GLOBAL,
                                         Gio.ThemedIcon.new(THEME + "group-photos.svg"),
                                         Unity.CategoryRenderer.VERTICAL_TILE))
        self._lens.props.categories = cats
        
        # Populate filters
        filters = []
        f2 = Unity.RadioOptionFilter.new ("date", FILTER_DATE, Gio.ThemedIcon.new("input-keyboard-symbolic"), False)
        f2.add_option ("7", FILTER_OPTION_7DAYS, None)
        f2.add_option ("30", FILTER_OPTION_30DAYS, None)
        f2.add_option ("180", FILTER_OPTION_6MONTHS, None)
        f2.add_option ("100000",FILTER_OPTION_OLDER, None)
        filters.append (f2)
        self._lens.props.filters = filters
        self._lens.export ()

        from shotwell_scope import Scope as shotwell
        shotwell (self._lens)

        from facebook_scope import Scope as facebook
        facebook (self._lens)

        from flickr_scope import Scope as flickr
        flickr (self._lens)

        from picasa_scope import Scope as picasa
        picasa (self._lens)

class Merger (GObject.Object, Unity.MergeStrategy):
    def __init__ (self):
        GObject.Object.__init__ (self)
        self.dedup = set()
        self.current_model = 0

    def cmp_time (self, a, b, c, d, title):
        try:
            previous = a[5].get_string ().split("_ulp-date_")[1]
            current = title.get_string ().split("_ulp-date_")[1]
            if previous > current:
                return -1
            else:
                return 1
        except:
            return 0

    def cmp_title (self, a, b, c, d, title):
        try:
            previous = a[4].get_string ()
            current = title.get_string ()
            if previous < current:
                return -1
            else:
                return 1
        except:
            return 0

    def do_merge_result (self, model, row, n_cols):
        # Clear the dedup model when we get a new results model
        if self.current_model > len(model) or len(model) < 1:
            self.dedup.clear ()
        self.current_model = len(model)
        dedup_size = len(self.dedup)
        self.dedup.add(str(row[1])+str(row[4]))
        if dedup_size < len(self.dedup):
            return model.insert_row_sorted(row, self.cmp_time,row[5])


if __name__ == "__main__":
    try:
        session_bus_connection = Gio.bus_get_sync (Gio.BusType.SESSION, None)
        session_bus = Gio.DBusProxy.new_sync (session_bus_connection, 0, None,
                                              'org.freedesktop.DBus',
                                              '/org/freedesktop/DBus',
                                              'org.freedesktop.DBus', None)
        result = session_bus.call_sync('RequestName',
                                       GLib.Variant ("(su)", (BUS_NAME, 0x4)),
                                       0, -1, None)
                                       
        # Unpack variant response with signature "(u)". 1 means we got it.
        result = result.unpack()[0]
        
        if result != 1 :
            print ("Failed to own name %s. Bailing out." % BUS_NAME, file=sys.stderr)
            raise SystemExit (1)
    except:
        raise SystemExit(1)

    daemon = Daemon()
    GObject.MainLoop().run()
