# Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018  Rickard Lindberg, Roger Lindberg
#
# This file is part of Timeline.
#
# Timeline 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.
#
# Timeline 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 Timeline.  If not, see <http://www.gnu.org/licenses/>.


from timelinelib.wxgui.framework import Controller


class EventsMoveController(Controller):

    def on_init(self, main_frame, db, config, preferred_category_name):
        self._main_frame = main_frame
        self._db = db
        self._config = config
        self._populate_view(preferred_category_name)

    def _populate_view(self, preferred_category_name):
        self.view.PopulateCategories(exclude=None)
        self.view.SelectCategory(0)
        self.view.SetStartTime(None)
        self.view.SetEndTime(None)
        self.view.SetPreferredCategory(preferred_category_name or self.view.ALL_CATEGORIES)

    def on_ok_clicked(self, evt):
        events = self._get_events()
        diff = self.view.GetEndTime() - self.view.GetStartTime()
        if diff.seconds != 0:
            for event in events:
                start = event.time_period.start_time + diff
                end =  event.time_period.end_time + diff
                event.update_period(start, end)
                event.save()
        self.view.EndModalOk()

    def _get_events(self):
        category = self.view.GetCategory()
        selected_event_ids = self._main_frame.view_properties.selected_event_ids
        events = self._db.get_all_events()
        if category is not None:
            events = [e for e in events
                      if e.get_category()
                      and e.id in selected_event_ids
                      and self._include(category.name, e.get_category())]
        else:
            events = [e for e in events if e.id in selected_event_ids]
        return events

    def _include(self, category_name, event_category):
        if event_category.name == category_name:
            return True
        else:
            if event_category.parent:
                return self._include(category_name, event_category.parent)
            else:
                return False
