# 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/>.


import wx

from timelinelib.canvas.data import TimePeriod
from timelinelib.canvas.drawing.rect import FloatingRect
from timelinelib.canvas.drawing.rect import Rect
from timelinelib.canvas.drawing.utils import Metrics
from timelinelib.features.experimental.experimentalfeatures import EXTENDED_CONTAINER_HEIGHT
from timelinelib.features.experimental.experimentalfeatures import EXTENDED_CONTAINER_STRATEGY


FORWARD = 1
BACKWARD = -1
MIN_W_PERIOD_EVENT = 2
ICON_PADDING = 5


class TimelineScene:

    def __init__(self, size, db, view_properties, get_text_size_fn, appearance):
        self._db = db
        self._view_properties = view_properties
        self._get_text_size_fn = get_text_size_fn
        self._appearance = appearance
        self._container_padding = 2
        if EXTENDED_CONTAINER_HEIGHT.enabled():
            self._container_title_height = self._get_text_height("")
        else:
            self._container_title_height = 0
        self._outer_padding = 5
        self._inner_padding = 3
        self._baseline_padding = 15
        self._period_threshold = 20
        self._data_indicator_size = 10
        self._metrics = Metrics(size, self._db.get_time_type(),
                                self._view_properties.displayed_period,
                                self._view_properties.divider_position)
        self.width, self.height = size
        self.divider_y = self._metrics.half_height
        self.event_data = []
        self.major_strip = None
        self.minor_strip = None
        self.major_strip_data = []
        self.minor_strip_data = []

    def get_event_text(self, event):
        if event.get_progress() == 100 and self._view_properties.get_display_checkmark_on_events_done():
            return "\u2714" + event.get_text()
        else:
            return event.get_text()

    @property
    def view_properties(self):
        return self._view_properties

    @property
    def appearance(self):
        return self._appearance

    def center_text(self):
        return self._appearance.get_center_event_texts()

    def draw_short_period_event_as_symbol_below_divider_line(self):
        return self._appearance.get_never_show_period_events_as_point_events()

    def draw_short_period_event_as_period_event(self):
        return (
            self._appearance.get_never_show_period_events_as_point_events()
            and
            self._appearance.get_text_to_the_left_of_period_events()
        )

    def set_outer_padding(self, outer_padding):
        self._outer_padding = outer_padding

    def set_inner_padding(self, inner_padding):
        self._inner_padding = inner_padding

    def get_baseline_padding(self):
        return self._baseline_padding

    def set_baseline_padding(self, baseline_padding):
        self._baseline_padding = baseline_padding

    def set_period_threshold(self, period_threshold):
        self._period_threshold = period_threshold

    def set_data_indicator_size(self, data_indicator_size):
        self._data_indicator_size = data_indicator_size

    def create(self):
        """
        Creating a scene means that pixel sizes and positions are calculated
        for events and strips.
        """
        self.event_data = self._calc_event_sizes_and_positions()
        self.minor_strip_data, self.major_strip_data = self._calc_strips_sizes_and_positions()

    def x_pos_for_time(self, time):
        return self._metrics.calc_x(time)

    def x_pos_for_now(self):
        return self.x_pos_for_time(self._db.now)

    def get_time(self, x):
        return self._metrics.get_time(x)

    def distance_between_times(self, time1, time2):
        time1_x = self._metrics.calc_exact_x(time1)
        time2_x = self._metrics.calc_exact_x(time2)
        distance = abs(time1_x - time2_x)
        return distance

    def width_of_period(self, time_period):
        return self._metrics.calc_width(time_period)

    def get_closest_overlapping_event(self, selected_event, up=True):
        rect = self._get_event_rect(selected_event)
        # self._get_event_rect() returns None if the selected event isn't visible.
        # (The selected event can be scrolled out of view). In this case the period
        # can't be calculated and because of that the direction and event can't be
        # calculated. Instead you get exceptions when trying to access rect attributes.
        # To avoid this situation we return event=None when no rect is found. 
        # The result on the GUI is that the event won't be moved vertically. And 
        # that's better then an exception!
        if rect is None: 
            return None, 1
        else:
            period = self._event_rect_drawn_as_period(rect)
            direction = self._get_direction(period, up)
            evt = self._get_overlapping_event(period, direction, selected_event, rect)
            return evt, direction

    def _get_event_rect(self, event):
        for event_rects in self.event_data:
            if event_rects.event == event:
                return event_rects.box_rect

    def _event_rect_drawn_as_period(self, event_rect):
        return event_rect.Y >= self.divider_y

    @staticmethod
    def _get_direction(period, up):
        if up:
            if period:
                direction = BACKWARD
            else:
                direction = FORWARD
        else:
            if period:
                direction = FORWARD
            else:
                direction = BACKWARD
        return direction

    def _get_overlapping_event(self, period, direction, selected_event, rect):
        event_data = self._get_overlapping_events_list(period, rect)
        return self._get_overlapping_event_from_list(event_data, direction, selected_event)

    def _get_overlapping_events_list(self, period, rect):
        if period:
            return self._get_list_with_overlapping_period_events(rect)
        else:
            return self._get_list_with_overlapping_point_events(rect)

    def _get_overlapping_event_from_list(self, event_data, direction, selected_event):
        if direction == FORWARD:
            return self._get_next_overlapping_event(event_data, selected_event)
        else:
            return self._get_prev_overlapping_event(event_data, selected_event)

    @staticmethod
    def _get_next_overlapping_event(event_data, selected_event):
        selected_event_found = False
        for event_rects in event_data:
            if not selected_event.is_subevent() and event_rects.event.is_subevent():
                continue
            if selected_event_found:
                return event_rects.event
            else:
                if event_rects.event == selected_event:
                    selected_event_found = True

    @staticmethod
    def _get_prev_overlapping_event(event_data, selected_event):
        prev_event = None
        for event_rects in event_data:
            if not selected_event.is_subevent() and event_rects.event.is_subevent():
                continue
            if event_rects.event == selected_event:
                return prev_event
            prev_event = event_rects.event

    def _calc_event_sizes_and_positions(self):
        self.events_from_db = self._db.get_events(self._view_properties.displayed_period)
        visible_events = self._view_properties.filter_events(self.events_from_db)
        visible_events = self._place_subevents_after_container(visible_events)
        return self._calc_event_rects(visible_events)

    def _place_subevents_after_container(self, events):
        """
        All subevents belonging to a container are placed directly after
        the container event in the events list.
        This is necessary because the position of the subevents are
        dependent on the position of the container. So the container metrics
        must be calculated first.
        """
        result = []
        for event in events:
            if event.is_container():
                result.append(event)
                subevents = [e for e in events if e.is_subevent() and e.container is event]
                result.extend(subevents)
            elif not event.is_subevent():
                result.append(event)
        return result

    def _calc_event_rects(self, events):
        self.event_data = self._calc_non_overlapping_event_rects(events)
        return self.event_data

    def _calc_non_overlapping_event_rects(self, events):
        self.event_data = []
        for event in events:
            event_rects = self._create_ideal_rect_for_event(event)
            self._prevent_overlapping_by_adjusting_rect_y(event_rects)
            self.event_data.append(event_rects)
        return self.event_data

    def _create_ideal_rect_for_event(self, event):
        self._reset_ends_today_when_start_date_is_in_future(event)
        if event.ends_today:
            event.set_end_time(self._db.now)
        if self._display_as_period(event):
            return self._calc_ideal_rect_for_period_event(event)
        else:
            if self._is_subevent_in_extended_container_strategy(event):
                event_rects = self._calc_ideal_rect_for_period_event(event)
                rw = self._calc_width_for_non_period_event(event)
                event_rects.box_rect.SetWidth(rw)
                event_rects.text_rect.SetWidth(rw)
                if not event.is_period():
                    self._extend_container_width_for_point_event(event_rects)
                return event_rects
            else:
                return self._calc_ideal_rect_for_non_period_event(event)

    def _extend_container_width_for_point_event(self, event_rects):
        """Make point events be enclosed by the container rectangle."""
        container_event_rects = self._get_container_data_for_subevent(event_rects.event)
        right_x_pos_diff = event_rects.bounding_rect.GetRight() - container_event_rects.box_rect.GetRight()
        if right_x_pos_diff > 0:
            container_event_rects.extend_width(right_x_pos_diff)

    def _reset_ends_today_when_start_date_is_in_future(self, event):
        if event.ends_today and self._start_date_is_in_future(event):
            event.ends_today = False

    def _start_date_is_in_future(self, event):
        return event.get_time_period().start_time > self._db.now

    def _display_as_period(self, event):
        if event.is_period():
            if self.draw_short_period_event_as_period_event():
                return True
            else:
                return self._metrics.calc_width(event.get_time_period()) > self._period_threshold
        else:
            return False

    def _calc_ideal_rect_for_period_event(self, event):
        rw = self._calc_width_for_period_event(event)
        rh = self._calc_height_for_period_event(event)
        rx = self._calc_x_pos_for_period_event(event)
        ry = self._calc_y_pos_for_period_event(event)
        if event.is_container():
            rh += self._container_title_height
            inflate = self._container_padding
        else:
            inflate = 0
        box_rect = self._calc_ideal_wx_rect(rx, ry, rw, rh)
        text_rect = box_rect.CloneDeflate(self._inner_padding, self._inner_padding)
        if self._appearance.get_text_to_the_left_of_period_events() and not event.is_container() and not event.is_subevent():
            tw, th = self._get_text_size(self.get_event_text(event))
            text_rect.X = box_rect.X - tw - self._inner_padding
            if self._has_icon_on_left_side(event):
                text_rect.X -= ICON_PADDING
            text_rect.Width = tw
        elif self.center_text():
            tw, th = self._get_text_size(self.get_event_text(event))
            text_rect.Width = min(text_rect.Width, tw)
            text_rect.X = box_rect.X + box_rect.Width // 2 - text_rect.Width // 2
        return EventRects(
            event=event,
            box_rect=box_rect.CloneInflate(inflate, inflate),
            text_rect=text_rect.CloneInflate(inflate, inflate),
            height_padding=self._outer_padding,
        )

    def _has_icon_on_left_side(self, event):
        return event.fuzzy_start or event.locked

    def _calc_width_for_period_event(self, event):
        return max(
            self._metrics.calc_width(event.get_time_period()),
            MIN_W_PERIOD_EVENT,
        )

    def _calc_height_for_period_event(self, event):
        return self._get_text_height(self.get_event_text(event)) + 2 * self._inner_padding

    def _calc_x_pos_for_period_event(self, event):
        return self._metrics.calc_x(event.get_time_period().start_time)

    def _calc_y_pos_for_period_event(self, event):
        if self._is_subevent_in_extended_container_strategy(event):
            return self._get_container_ry(event)
        if event.is_subevent():
            if event.is_period():
                return self._get_container_ry(event)
            else:
                return self._metrics.half_height - self._baseline_padding - self._outer_padding
        else:
            return self._metrics.half_height + self._baseline_padding + self._outer_padding

    def _get_container_ry(self, subevent):
        for event_rect in self.event_data:
            if event_rect.event == subevent.container:
                return event_rect.box_rect.y
        return self._metrics.half_height + self._baseline_padding + self._outer_padding

    def _calc_ideal_rect_for_non_period_event(self, event):
        if self.draw_short_period_event_as_symbol_below_divider_line() and event.is_period():
            x = self.x_pos_for_time(event.mean_time())
            y0 = self.divider_y
            y1 = y0 + 10
            rect = FloatingRect(x - 5, y1 - 5, 10, 10)
        else:
            rw = self._calc_width_for_non_period_event(event)
            rh = self._calc_height_for_non_period_event(event)
            rx = self._calc_x_pos_for_non_period_event(event, rw)
            ry = self._calc_y_pos_for_non_period_event(event, rh)
            if event.is_milestone():
                rect = Rect(rx, ry, rw, rh)
                rect.SetWidth(rect.GetHeight())
                rect.SetX(self._metrics.calc_x(event.get_time_period().start_time) - rect.Width // 2)
                rect = FloatingRect(rect)
            else:
                rect = self._calc_ideal_wx_rect(rx, ry, rw, rh)
        return EventRects(
            event=event,
            box_rect=rect,
            text_rect=rect.CloneDeflate(self._inner_padding, self._inner_padding),
            height_padding=self._outer_padding,
        )

    def _calc_width_for_non_period_event(self, event):
        tw, th = self._get_text_size(self.get_event_text(event))
        rw = tw + 2 * self._inner_padding
        if event.has_data():
            rw += self._data_indicator_size // 3
        if event.get_fuzzy() or event.get_locked():
            rw += th + 2 * self._inner_padding
        return rw

    def _calc_height_for_non_period_event(self, event):
        return self._get_text_height(self.get_event_text(event)) + 2 * self._inner_padding

    def _calc_x_pos_for_non_period_event(self, event, rw):
        if self._appearance.get_draw_period_events_to_right():
            return self._metrics.calc_x(event.get_time_period().start_time)
        else:
            return self._metrics.calc_x(event.mean_time()) - rw // 2

    def _calc_y_pos_for_non_period_event(self, event, rh):
        if event.is_milestone():
            return self._metrics.half_height - rh // 2
        else:
            return self._metrics.half_height - rh - self._baseline_padding - self._outer_padding

    def _get_text_size(self, text):
        if len(text) > 0:
            return self._get_text_size_fn(text)
        else:
            return self._get_text_size_fn(" ")

    def _get_text_height(self, text):
        return self._get_text_size(text)[1]

    def _calc_ideal_wx_rect(self, rx, ry, rw, rh):
        # Drawing stuff on huge x-coordinates causes drawing to fail.
        # MARGIN must be big enough to hide outer padding, borders, and
        # selection markers.
        MARGIN = 8
        if rx < (-MARGIN):
            move_distance = abs(rx) - MARGIN
            rx = rx + move_distance
            rw = rw - move_distance
        right_edge_x = rx + rw
        if right_edge_x > self.width + MARGIN:
            rw = rw - right_edge_x + self.width + MARGIN
        return Rect(rx, ry, rw, rh)

    def _calc_strips_sizes_and_positions(self):
        """Fill the two arrays `minor_strip_data` and `major_strip_data`."""

        def fill(strip_list, strip):
            """Fill the given list with the given strip."""
            try:
                current_start = strip.start(self._view_properties.displayed_period.start_time)
                while current_start < self._view_properties.displayed_period.end_time:
                    next_start = strip.increment(current_start)
                    strip_list.append(TimePeriod(current_start, next_start))
                    current_start = next_start
            except:
                # Exception occurs when major=century and when we are at the end of the calendar
                pass
        major_strip_data = []  # List of time_period
        minor_strip_data = []  # List of time_period
        self.major_strip, self.minor_strip = self._db.get_time_type().choose_strip(self._metrics, self._appearance)
        if hasattr(self.major_strip, 'set_skip_s_in_decade_text'):
            self.major_strip.set_skip_s_in_decade_text(self._view_properties.get_skip_s_in_decade_text())
        if hasattr(self.minor_strip, 'set_skip_s_in_decade_text'):
            self.minor_strip.set_skip_s_in_decade_text(self._view_properties.get_skip_s_in_decade_text())
        fill(major_strip_data, self.major_strip)
        fill(minor_strip_data, self.minor_strip)
        return minor_strip_data, major_strip_data

    def minor_strip_is_day(self):
        return self.minor_strip.is_day()

    def is_weekend_day(self, time):
        return time.is_weekend_day

    def get_hidden_event_count(self):
        visible_events_count = len([
            event_rects
            for event_rects
            in self.event_data
            if event_rects.box_rect.Y < self.height and (event_rects.box_rect.Y + event_rects.box_rect.Height) > 0
        ])
        return len(self.events_from_db) - visible_events_count

    def _prevent_overlapping_by_adjusting_rect_y(self, event_rects):
        if event_rects.box_rect.is_allowed_to_overlap():
            return
        if self._is_subevent_in_extended_container_strategy(event_rects.event):
            self._adjust_subevent_rect(event_rects)
        elif event_rects.event.is_subevent() and self._display_as_period(event_rects.event):
            self._adjust_subevent_rect(event_rects)
        else:
            if self._display_as_period(event_rects.event):
                self._adjust_period_rect(event_rects)
            else:
                self._adjust_point_rect(event_rects)

    def _adjust_period_rect(self, event_rects):
        rect = self._get_overlapping_period_rect_with_largest_y(event_rects.bounding_rect)
        if rect is not None:
            event_rects.set_bounding_y(rect.Y + rect.height)

    def _adjust_subevent_rect(self, event_rects):
        container_event_rects = self._get_container_data_for_subevent(event_rects.event)
        event_rects.set_bounding_y(
            container_event_rects.box_rect.Y
            +
            self._container_padding
            +
            self._container_title_height
            -
            event_rects.height_padding
        )
        rect = self._get_overlapping_subevent_rect_with_largest_y(event_rects)
        if rect is not None:
            event_rects.set_bounding_y(rect.Y + rect.height)
            subevent_box_bottom = event_rects.box_rect.Bottom
            container_box_bottom = container_event_rects.box_rect.Bottom
            diff = subevent_box_bottom - container_box_bottom + self._container_padding
            if diff > 0:
                container_event_rects.extend_box_height(diff)

    def _get_overlapping_subevent_rect_with_largest_y(self, event_rects):
        event_data = self._get_list_with_overlapping_subevents(event_rects)
        rect_with_largest_y = None
        for event_rects in event_data:
            if rect_with_largest_y is None or event_rects.bounding_rect.Y > rect_with_largest_y.Y:
                rect_with_largest_y = event_rects.bounding_rect
        return rect_with_largest_y

    def _get_overlapping_period_rect_with_largest_y(self, event_rect):
        event_data = self._get_list_with_overlapping_period_events(event_rect)
        rect_with_largest_yh = None
        for event_rects in event_data:
            if rect_with_largest_yh is None or event_rects.bounding_rect.Y + event_rects.bounding_rect.Height > rect_with_largest_yh.Y + rect_with_largest_yh.Height:
                rect_with_largest_yh = event_rects.bounding_rect
        return rect_with_largest_yh

    def _get_list_with_overlapping_period_events(self, event_rect):
        return [
            event_rects
            for event_rects
            in self.event_data
            if (
                self._rects_overlap(event_rect, event_rects.bounding_rect)
                and
                event_rects.bounding_rect.Y >= self.divider_y
            )
        ]

    def _get_list_with_overlapping_subevents(self, event_rects):
        return [
            inner_event_rects
            for inner_event_rects
            in self.event_data
            if (
                inner_event_rects.event.is_subevent()
                and
                inner_event_rects.event.container is event_rects.event.container
                and
                self._rects_overlap(event_rects.bounding_rect, inner_event_rects.bounding_rect)
                and
                inner_event_rects.bounding_rect.Y >= self.divider_y
            )
        ]

    def _adjust_point_rect(self, event_rects):
        rect = self._get_overlapping_point_rect_with_smallest_y(event_rects.bounding_rect)
        if rect is not None:
            event_rects.set_bounding_y(rect.Y - event_rects.bounding_rect.height)

    def _get_overlapping_point_rect_with_smallest_y(self, event_rect):
        event_data = self._get_list_with_overlapping_point_events(event_rect)
        rect_with_smallest_y = None
        for event_rects in event_data:
            if rect_with_smallest_y is None or event_rects.bounding_rect.Y < rect_with_smallest_y.Y:
                rect_with_smallest_y = event_rects.bounding_rect
        return rect_with_smallest_y

    def _get_list_with_overlapping_point_events(self, event_rect):
        return [
            event_rects
            for event_rects
            in self.event_data
            if (
                self._rects_overlap(event_rect, event_rects.bounding_rect)
                and
                event_rects.bounding_rect.Y < self.divider_y
                and
                not event_rects.box_rect.is_allowed_to_overlap()
            )
        ]

    def _rects_overlap(self, rect1, rect2):
        REMOVE_X_PADDING = 2
        return (rect2.x + REMOVE_X_PADDING <= rect1.x + rect1.width and
                rect1.x + REMOVE_X_PADDING <= rect2.x + rect2.width)

    def _is_subevent_in_extended_container_strategy(self, event):
        return EXTENDED_CONTAINER_STRATEGY.enabled() and event.is_subevent()

    def _get_container_data_for_subevent(self, subevent):
        return [
            event_rects
            for event_rects
            in self.event_data
            if event_rects.event is subevent.container
        ][0]


class EventRects:

    def __init__(self, event, box_rect, text_rect, height_padding):
        self.event = event
        self.box_rect = box_rect
        self.text_rect = text_rect
        self.height_padding = height_padding

    @property
    def bounding_rect(self):
        """
        >>> box_rect = Rect(0, 0, 10, 10)
        >>> text_rect = Rect(10, 10, 10, 10)
        >>> event_rects = EventRects(event=None, box_rect=box_rect, text_rect=text_rect, height_padding=5)
        >>> event_rects.bounding_rect
        wx.Rect(0, -5, 20, 30)
        """
        min_x = min([self.box_rect.X, self.text_rect.X])
        min_y = min([self.box_rect.Y, self.text_rect.Y])
        max_right = max([self.box_rect.Right, self.text_rect.Right])
        max_bottom = max([self.box_rect.Bottom, self.text_rect.Bottom])
        return Rect(
            x=min_x,
            y=min_y,
            width=max_right-min_x+1,
            height=max_bottom-min_y+1,
        ).CloneInflate(0, self.height_padding)

    def set_bounding_y(self, y):
        """
        >>> box_rect = Rect(0, 0, 10, 5)
        >>> text_rect = Rect(0, 0, 10, 5)
        >>> event_rects = EventRects(event=None, box_rect=box_rect, text_rect=text_rect, height_padding=5)

        >>> event_rects.box_rect
        wx.Rect(0, 0, 10, 5)
        >>> event_rects.bounding_rect
        wx.Rect(0, -5, 10, 15)

        >>> event_rects.set_bounding_y(5)
        >>> event_rects.box_rect
        wx.Rect(0, 10, 10, 5)
        >>> event_rects.bounding_rect
        wx.Rect(0, 5, 10, 15)
        """
        self.move_y(y - self.bounding_rect.Y)

    def extend_box_height(self, height):
        self.box_rect.Height += height

    def extend_width(self, widht):
        self.box_rect.Width += widht
        self.text_rect.Width += widht

    def move_y(self, amount):
        self.box_rect.Y += amount
        self.text_rect.Y += amount

    def text_outside_box(self):
        return self.text_rect.X < self.box_rect.X
