# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2001-2007  Donald N. Allingham
# Copyright (C) 2008       Gary Burton
# Copyright (C) 2011       Tim G L Lyons
# Copyright (C) 2017       Alois Poettker
#
# 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 2 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

"""
Provide the event view.
"""

#-------------------------------------------------------------------------
#
# Standard python modules
#
#-------------------------------------------------------------------------
import logging
_LOG = logging.getLogger(".plugins.eventview")

#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.sgettext

from gramps.gui.dialog import ErrorDialog, MultiSelectDialog, QuestionDialog
from gramps.gen.db import DbTxn
from gramps.gen.errors import WindowActiveError
from gramps.gen.lib import Event
from gramps.gen.utils.string import data_recover_msg

from gramps.gui.ddtargets import DdTargets
from gramps.gui.editors import EditEvent, DeleteEventQuery
from gramps.gui.filters.sidebar import EventSidebarFilter
from gramps.gui.merge import MergeEvent
from gramps.gen.plug import CATEGORY_QR_EVENT
from gramps.gui.views.bookmarks import EventBookmarks
from gramps.gui.views.listview import ListView, TEXT, MARKUP, ICON
from gramps.gui.views.treemodels import EventModel

#-------------------------------------------------------------------------
#
# EventView
#
#-------------------------------------------------------------------------
class EventView(ListView):
    """
    EventView class, derived from the ListView
    """
    # columns in the model used in view
    COL_DESCR = 0
    COL_ID = 1
    COL_TYPE = 2
    COL_DATE = 3
    COL_PLACE = 4
    COL_PRIV = 5
    COL_TAGS = 6
    COL_CHAN = 7
    COL_PARTIC = 8
    # column definitions
    COLUMNS = [
        (_('Description'), TEXT, None),
        (_('ID'), TEXT, None),
        (_('Type'), TEXT, None),
        (_('Date'), MARKUP, None),
        (_('Place'), TEXT, None),
        (_('Private'), ICON, 'gramps-lock'),
        (_('Tags'), TEXT, None),
        (_('Last Changed'), TEXT, None),
        (_('Main Participants'), TEXT, None),
        ]
    # default setting with visible columns, order of the col, and their size
    CONFIGSETTINGS = (
        ('columns.visible', [COL_TYPE, COL_PARTIC, COL_DATE, COL_PLACE,
                             COL_DESCR, COL_ID]),
        ('columns.rank', [COL_TYPE, COL_PARTIC, COL_DATE, COL_PLACE, COL_DESCR,
                          COL_ID, COL_PRIV, COL_TAGS, COL_CHAN]),
        ('columns.size', [100, 230, 150, 200, 100, 75, 40, 100, 100])
        )
    ADD_MSG = _("Add a new event")
    EDIT_MSG = _("Edit the selected event")
    DEL_MSG = _("Delete the selected event")
    MERGE_MSG = _("Merge the selected events")
    FILTER_TYPE = "Event"
    QR_CATEGORY = CATEGORY_QR_EVENT

    def __init__(self, pdata, dbstate, uistate, nav_group=0):
        """
        Create the Event View
        """
        signal_map = {
            'event-add'     : self.row_add,
            'event-update'  : self.row_update,
            'event-delete'  : self.row_delete,
            'event-rebuild' : self.object_build,
            'person-update' : self.person_update,
            'person-add'    : self.person_update,
            'person-delete' : self.object_build,  # TODO slow way to do this
            'family-update' : self.family_update,
            'family-add'    : self.family_update,
            'family-delete' : self.object_build,  # TODO slow way to do this
   
         'place-update'  : self.related_update,
            }

        ListView.__init__(
            self
, _('Events'), pdata, dbstate, uistate,
            EventModel,
            signal_map,
            EventBookmarks, nav_group,
            multiple=True,
            filter_class=EventSidebarFilter)

        uistate.connect('nameformat-changed', self.build_tree)
        uistate.connect('placeformat-changed', self.build_tree)

        self.additional_uis.append(self.additional_ui)

    def person_update(self, hndl_list):
        """ Deal with person updates thay may effect the Main Participants
        column.  These cannot use the more generic mechanism because Person
        objects use EventRef to point to events, rather than Events pointing
        to persons. Example: A person's name change or add event to person"""
        update_list = []
        for hndl in hndl_list:
            person = self.dbstate.db.get_person_from_handle(hndl)
            for eventref in person.get_event_ref_list():
                update_list.append(eventref.ref)
        self.row_update(update_list)

    def family_update(self, hndl_list):
        """ Deal with family updates thay may effect the Main Participants
        column.  These cannot use the more generic mechanism because Family
        objects use EventRef to point to events, rather than Events pointing
        to Families. Example: Change/add/removal of parent, or add family to
        event"""
        update_list = []
        for hndl in hndl_list:
            family = self.dbstate.db.get_family_from_handle(hndl)
            for eventref in family.get_event_ref_list():
                update_list.append(eventref.ref)
        self.row_update(update_list)

    def navigation_type(self):
        return 'Event'

    def drag_info(self):
        """
        Indicate that the drag type is an EVENT
        """
        return DdTargets.EVENT

    def get_stock(self):
        """
        Use the gramps-event stock icon
        """
        return 'gramps-event'

    additional_ui = [  # Defines the UI string for UIManager
        '''
      <placeholder id="LocalExport">
        <item>
          <attribute name="action">win.ExportTab</attribute>
          <attribute name="label" translatable="yes">Export View...</attribute>
        </item>
      </placeholder>
''',
        '''
      <section id="AddEditBook">
        <item>
          <attribute name="action">win.AddBook</attribute>
          <attribute name="label" translatable="yes">_Add Bookmark</attribute>
        </item>
        <item>
          <attribute name="action">win.EditBook</attribute>
          <attribute name="label" translatable="no">%s...</attribute>
        </item>
      </section>
''' % _('Organize Bookmarks'),
        '''
      <placeholder id="CommonGo">
      <section>
        <item>
          <attribute name="action">win.Back</attribute>
          <attribute name="label" translatable="yes">_Back</attribute>
        </item>
        <item>
          <attribute name="action">win.Forward</attribute>
          <attribute name="label" translatable="yes">_Forward</attribute>
        </item>
      </section>
      </placeholder>
''',
        '''
      <section id='CommonEdit' groups='RW'>
        <item>
          <attribute name="action">win.Add</attribute>
          <attribute name="label" translatable="yes">_Add...</attribute>
        </item>
        <item>
          <attribute name="action">win.Edit</attribute>
          <attribute name="label">%s</attribute>
        </item>
        <item>
          <attribute name="action">win.Remove</attribute>
          <attribute name="label" translatable="yes">_Delete</attribute>
        </item>
        <item>
          <attribute name="action">win.Merge</attribute>
          <attribute name="label" translatable="yes">_Merge...</attribut