#!/usr/bin/env python
# -*- coding: utf8 -*-

import gtk
import gtk.glade
import pango
import webbrowser
import os

from config import *
from ZIFile import *
from FileFactory import *

class MainWindow:

    def __init__(self, gladefile):
        self.__gladefile = gladefile
        self.__wTree = gtk.glade.XML(self.__gladefile, "MainWindow")
        self.__dTree = gtk.glade.XML(self.__gladefile, "ConvertChooser")
        self.__nTree = gtk.glade.XML(self.__gladefile, \
                "NonlinearityAlgorithmChooser")

        self.__convert_dialog = None
        self.__nonlinearity_check_dialog = None

        self.prepare_main_window()
        self.prepare_text_views()
        self.prepare_about_dialog()
        self.prepare_open_dialog()
        self.connect_events()

    def connect_events(self):
        # Events dictionary
        events = {
            "on_MainWindow_destroy" : gtk.main_quit,
            "on_QuitMenuItem_activate" : gtk.main_quit,
            "on_AboutMenuItem_activate" :
                self.on_AboutMenuItem_activate,
            "on_OpenMenuItem_activate" :
                self.on_OpenMenuItem_activate,
            "on_OpenToolButton_clicked" :
                self.on_OpenMenuItem_activate,
            "on_ConvertToolButton_clicked" :
                self.on_ConvertToolButton_clicked,
            "on_SaveToolButton_clicked" :
                self.on_SaveToolButton_clicked,
            "on_SaveMenuItem_activate" :
                self.on_SaveToolButton_clicked,
            "on_NonlinearityToolButton_clicked" :
                self.on_NonlinearityToolButton_clicked,
            "on_HelpMenuItem_activate" :
                self.on_Help_activate,
            "on_HelpToolButton_clicked" :
                self.on_Help_activate,
        }
        self.__wTree.signal_autoconnect(events)

    def prepare_main_window(self):
        self.__window = self.__wTree.get_widget("MainWindow")

        self.__save_button = self.__wTree.get_widget("SaveToolButton")
        self.__save_button.set_sensitive(False)
        self.__save_menu_item = self.__wTree.get_widget("SaveMenuItem")
        self.__save_menu_item.set_sensitive(False)

        self.__convert_button = \
                self.__wTree.get_widget("ConvertToolButton")
        self.__convert_button.set_sensitive(False)

        self.__nonlinearity_check_button = \
                self.__wTree.get_widget("NonlinearityToolButton")
        self.__nonlinearity_check_button.set_sensitive(False)

        self.__window.show()

    def prepare_about_dialog(self):
        self.__about_dialog = gtk.AboutDialog()
        self.__about_dialog.set_name(NAME)
        self.__about_dialog.set_version(VERSION)
        self.__about_dialog.set_comments(DESCRIPTION)
        self.__about_dialog.set_license(LICENSE)
        self.__about_dialog.set_copyright("Copyright © 2007 " \
                + AUTHOR)
        self.__about_dialog.set_website("http://user.sheep.art.pl")
        self.__about_dialog.set_authors([AUTHOR \
                + ' <' + AUTHOR_EMAIL + '>'])

    def prepare_open_dialog(self):
        self.__open_dialog = gtk.FileChooserDialog(
                "Otwórz plik do konwersji",
                self.__window)
        self.__open_dialog.add_buttons(
                gtk.STOCK_OPEN, gtk.RESPONSE_OK,
                gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
        self.__open_dialog.set_default_response(gtk.RESPONSE_OK)

    def prepare_save_dialog(self):
        self.__save_dialog = gtk.FileChooserDialog(
                "Zapisz przekonwertowany plik",
                self.__window,
                gtk.FILE_CHOOSER_ACTION_SAVE)
        self.__save_dialog.add_buttons(
                gtk.STOCK_SAVE, gtk.RESPONSE_OK,
                gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
        self.__save_dialog.set_default_response(gtk.RESPONSE_OK)
        self.__save_dialog.set_do_overwrite_confirmation(True)

        filter = gtk.FileFilter()
        filter.set_name(self.converted.name)
        filter.add_pattern('*.' + self.converted.extension)
        self.__save_dialog.add_filter(filter)

    def prepare_dialog_from_choices(self, vbox, choices, name=None):
        # Clear the last content.
        vbox.foreach(vbox.remove)

        first_button = gtk.RadioButton(None, choices.pop())
        vbox.add(first_button)
        for choice in choices:
            if choice != name:
                vbox.add(gtk.RadioButton(first_button, choice))

        vbox.show_all()

    def prepare_convert_dialog(self):
        if self.__convert_dialog is None:
            self.__convert_dialog = \
                    self.__dTree.get_widget("ConvertChooser")

            self.button_vbox = self.__dTree.get_widget("MainVBox")

        self.prepare_dialog_from_choices(
                self.button_vbox,
                [value.name for value in parsers.values()],
                self.tmp.name
            )


    def prepare_nonlinearity_check_dialog(self):
        if self.__nonlinearity_check_dialog is None:
            self.__nonlinearity_check_dialog = \
                    self.__nTree.get_widget("NonlinearityAlgorithmChooser")

            self.checkers_vbox = self.__nTree.get_widget("MainVBox")

        self.prepare_dialog_from_choices(
                self.checkers_vbox,
                [value.name for value in checkers.values()]
            )

    def prepare_text_views(self):
        tag_table = gtk.TextTagTable()
        mono_tag = gtk.TextTag("mono")
        mono_tag.set_property("font", "Monospace")
        tag_table.add(mono_tag)

        self.__original_text_buffer = gtk.TextBuffer(tag_table)
        self.__original_text_view = self.__wTree.get_widget(
                "OriginalTextView")
        self.__original_text_view.set_buffer(
                self.__original_text_buffer)
        self.__converted_text_buffer = gtk.TextBuffer(tag_table)
        self.__converted_text_view = self.__wTree.get_widget(
                "ConvertedTextView")
        self.__converted_text_view.set_buffer(
                self.__converted_text_buffer)

    def on_AboutMenuItem_activate(self, widget):
        self.__about_dialog.run()
        self.__about_dialog.hide()

    def on_OpenMenuItem_activate(self, widget):
        response = self.__open_dialog.run()
        self.__open_dialog.hide()

        if response == gtk.RESPONSE_OK:
            filename = self.__open_dialog.get_filename()

            factory = FileFactory()
            self.tmp = factory.get_parser(filename.rsplit('.')[-1])

            content = self.tmp.load_file(filename)

            self.__original_text_buffer.delete(
                    self.__original_text_buffer.get_start_iter(),
                    self.__original_text_buffer.get_end_iter()
                )
            self.__converted_text_buffer.delete(
                    self.__converted_text_buffer.get_start_iter(),
                    self.__converted_text_buffer.get_end_iter()
                )

            self.__original_text_buffer.insert_with_tags_by_name(
                    self.__original_text_buffer.get_start_iter(),
                    content,
                    "mono"
                )

            self.on_file_parsed()

    def on_SaveToolButton_clicked(self, widget):
        response = self.__save_dialog.run()
        self.__save_dialog.hide()
        if response == gtk.RESPONSE_OK:
            filename = self.__save_dialog.get_filename()

            if not filename.endswith('.' + self.converted.extension):
                filename += '.' + self.converted.extension

            self.converted.save_file(filename)

    def on_file_parsed(self):
        self.prepare_convert_dialog()
        self.prepare_nonlinearity_check_dialog()

        self.__convert_button.set_sensitive(True)
        self.__nonlinearity_check_button.set_sensitive(True)

    def on_ConvertToolButton_clicked(self, widget):
        response = self.__convert_dialog.run()
        self.__convert_dialog.hide()

        if response == gtk.RESPONSE_ACCEPT:
            for child in self.button_vbox.get_children():
                if child.get_active():
                    convert_type = child.get_label()
                    break

            conv = FunctionConverter()
            self.converted = conv.convert(convert_type, self.tmp.convert_to_FP())
            content = self.converted.parse_out()

            self.__converted_text_buffer.delete(
                    self.__converted_text_buffer.get_start_iter(),
                    self.__converted_text_buffer.get_end_iter()
                )

            self.__converted_text_buffer.insert_with_tags_by_name(
                    self.__converted_text_buffer.get_start_iter(),
                    content,
                    "mono"
                )

            self.prepare_save_dialog()
            self.__save_button.set_sensitive(True)
            self.__save_menu_item.set_sensitive(True)

    def on_NonlinearityToolButton_clicked(self, widget):
        response = self.__nonlinearity_check_dialog.run()
        self.__nonlinearity_check_dialog.hide()

        if response == gtk.RESPONSE_ACCEPT:
            for child in self.checkers_vbox.get_children():
                if child.get_active():
                    check_type = child.get_label()
                    break

            checker = FunctionChecker()
            self.converted = checker.check(check_type,
                    self.tmp.convert_to_FP())
            content = self.converted.parse_out()

            self.__converted_text_buffer.delete(
                    self.__converted_text_buffer.get_start_iter(),
                    self.__converted_text_buffer.get_end_iter()
                )

            self.__converted_text_buffer.insert_with_tags_by_name(
                    self.__converted_text_buffer.get_start_iter(),
                    content,
                    "mono"
                )

        self.prepare_nonlinearity_check_dialog()

    def on_Help_activate(self, widget):
        webbrowser.open(
                'file:///'
                + os.getcwd()
                + os.path.join('/help', 'index.html'))
