#!/usr/bin/python
# -*- coding: utf-8 -*-
### BEGIN LICENSE
# Copyright (C) 2009 Jono Bacon <jono@ubuntu.com>
# Copyright (C) 2010 Michael Budde <mbudde@gmail.com>
#
#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 gtk
import gobject
import pango
import time
import re

from lernid.widgets.Widget import Widget
from lernid.LernidPreferences import Preferences

from lernid import IrcBackend

class IrcWidget(Widget):

    def get_hand_cursor(self):
        if not hasattr(self, "_hand_cursor"):
            self._hand_cursor = gtk.gdk.Cursor(gtk.gdk.HAND2)
        return self._hand_cursor

    def get_regular_cursor(self):
        if not hasattr(self, "_regular_cursor"):
            self._regular_cursor = gtk.gdk.Cursor(gtk.gdk.XTERM)
        return self._regular_cursor

    def do_event_connect(self, event_man, event):
        self._browser = event_man.get_widget_by_name('browser')
        self.get_toplevel().connect('focus-out-event', self._focus_out)
        schedule = event_man.get_widget_by_name('schedule')
        self._on_faculty = schedule.on_faculty # retrieve method
        self._classbotnames = event_man.classbotnames


    def _init_hyperlinks(self):
        hyperlink_tag = self._buffer.create_tag('hyperlink', foreground='#0000ff',
                                                underline=pango.UNDERLINE_SINGLE)
        self._buffer.connect('mark-set', self._mark_set, hyperlink_tag)
        self._textview.connect('motion-notify-event', self._motion_notify, hyperlink_tag)
        self._textview.connect('expose-event', self._draw_red_line)

        self._red_line_mark = self._buffer.create_mark(None, self._buffer.get_end_iter(), True)
        self._visited_since_last_update = False

    def _append_to_buffer(self, text, sender=None, msgtype=None):
        iend = self._buffer.get_end_iter()
        if self._visited_since_last_update and not self.get_toplevel().is_active():
            self._buffer.move_mark(self._red_line_mark, iend)
            self._textview.queue_draw()
            self._visited_since_last_update = False
        if Preferences.get('show_irc_time'):
            self._buffer.insert(iend, '\n[{0}] '.format(time.strftime(_('%H:%M'))))
        else:
            self._buffer.insert(iend, '\n')
        if msgtype == IrcBackend.Channel.TYPE_ACTION:
            self._buffer.insert(iend, ' * ')
            if sender:
                self._buffer.insert_with_tags_by_name(iend, sender+' ', 'gray')
            start_pos = iend.get_offset()
            self._buffer.insert(iend, text)
        else:
            if sender:
                self._buffer.insert_with_tags_by_name(iend, '<%s> ' % sender, 'gray')
                start_pos = iend.get_offset()
                my_nick = self._chan._conn._acquired_nick
                if text.startswith(my_nick) and sender.lower() in self._classbotnames:
                    self._buffer.insert_with_tags_by_name(iend, text, 'highlight','italicize')
                elif my_nick in text and sender != my_nick:
                    self._buffer.insert_with_tags_by_name(iend, text, 'highlight')
                elif self._on_faculty(sender):
                    self._buffer.insert_with_tags_by_name(iend, text, 'highlight')
                elif sender.lower() in self._classbotnames:
                    self._buffer.insert_with_tags_by_name(iend, text, 'italicize')
                else: self._buffer.insert(iend, text)
            else:
                self._buffer.insert(iend, text)

        if type(text)!=unicode:
            text=unicode(text, 'utf-8')
        for url in re.finditer(r"https?://\S+", text):
            self._buffer.apply_tag_by_name('hyperlink',
                self._buffer.get_iter_at_offset(start_pos + url.start()),
                self._buffer.get_iter_at_offset(start_pos + url.end()))

        self._at_bottom = (self._adjust.value == self._adjust.upper -
                           self._adjust.page_size)

    def _mark_set(self, buf, text_iter, mark, tag):
        if mark.get_name() == 'insert' and text_iter.has_tag(tag) and len(buf.get_selection_bounds()) == 0:
            text_iter.backward_to_tag_toggle(tag)
            istart = text_iter.copy()
            text_iter.forward_to_tag_toggle(tag)
            self._browser.set_location(buf.get_text(istart, text_iter))

    def _motion_notify(self, text_view, event, tag):
        x, y = text_view.window_to_buffer_coords(gtk.TEXT_WINDOW_WIDGET,
            int(event.x), int(event.y))
        iter = text_view.get_iter_at_location(x, y)
        if (iter.has_tag(tag)):
            text_view.get_window(gtk.TEXT_WINDOW_TEXT).set_cursor(self.get_hand_cursor())
        else:
            text_view.get_window(gtk.TEXT_WINDOW_TEXT).set_cursor(self.get_regular_cursor())
        return False

    def _focus_out(self, widget, event):
        self._visited_since_last_update = True
        return False

    def _draw_red_line(self, widget, event):
        if self._buffer.get_char_count() > 0:
            iter = self._buffer.get_iter_at_mark(self._red_line_mark)
            if (iter.get_offset() > 0):
                top, h = self._textview.get_line_yrange(iter)
                w_x, w_y = self._textview.buffer_to_window_coords(gtk.TEXT_WINDOW_TEXT, 0, top + h)
                win = self._textview.get_window(gtk.TEXT_WINDOW_TEXT)
                gc = gtk.gdk.GC(win)
                gc.set_rgb_fg_color(gtk.gdk.Color('darkred'))
                win.draw_line(gc, 0, w_y, (win.get_size())[0], w_y)
