# Copyright (C) 2003, 2004, 2008 by Intevation GmbH
# Authors:
# Didrik Pinte <dpinte@dipole-consulting.com> (2008)
# Jan-Oliver Wagner <jan@intevation.de> (2003, 2004)
# Bernhard Herzog <bh@intevation.de> (2004)
# Martin Schulze <joey@infodrom.org> (2004)
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with Thuban for details.

"""
Provide layers via OGC WMS.
"""

__version__ = "$Revision: 2848 $"
# $Source$
# $Id: wms.py 2848 2008-06-23 08:26:42Z dpinte $

import os, sys
import xml.dom.minidom
import tempfile

import wx

from Thuban.Model.proj import Projection
from Thuban.Model.extension import Extension
from Thuban.UI.command import registry, Command
from Thuban.UI.mainwindow import main_menu, layer_properties_dialogs
from Thuban import _
import Thuban.UI.baserenderer

from layer import WMSLayer


class WMSExtension(Extension):
    def TreeInfo(self):
        return (_("Extension: %s") % self.title,
                [ object.TreeInfo() for object in self.objects ])


def render_wms_layer(renderer, layer):
    offx, offy = renderer.offset
    width, height = renderer.dc.GetSizeTuple()

    scale = renderer.scale
    xmin = (0 - offx) / scale
    ymin = (offy - height) / scale
    xmax = (width - offx) / scale
    ymax = (offy - 0) / scale

    img, format = layer.GetMapImg(width, height, (xmin, ymin, xmax, ymax))

    data = (width, height, (img, None, None))

    renderer.draw_raster_data(0,0, data, format)

    return ()

Thuban.UI.baserenderer.add_renderer_extension(WMSLayer, render_wms_layer)
from properties import wmsProperties
layer_properties_dialogs.add(WMSLayer, wmsProperties)


class SelectWMSServer(wx.Dialog):

    ID_COMBOVALUE = 4003

    def __init__(self, parent):
        wx.Dialog.__init__(self, parent, -1, _("Select WMS Server"),
            style = wx.DEFAULT_DIALOG_STYLE
                  | wx.SYSTEM_MENU
                  | wx.RESIZE_BORDER)

        self.combo_value = wx.ComboBox(self, self.ID_COMBOVALUE, size=(500,-1))
        self.combo_value.Append("")
        self.combo_value.Append('http://demo.intevation.org/cgi-bin/frida-wms')
        self.combo_value.Append('http://wms.jpl.nasa.gov/wms.cgi')
        self.combo_value.SetSelection(0)

        button_ok = wx.Button(self, wx.ID_OK, _("OK"))
        button_ok.SetDefault()
        button_close = wx.Button(self, wx.ID_CANCEL, _("Close"))

        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(self.combo_value, 1, wx.EXPAND|wx.ALL|wx.CB_SORT, 10)
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add(button_ok, 0, wx.ALL, 10)
        hbox.Add(button_close, 0, wx.ALL, 10)
        vbox.Add(hbox, 0, 10)

        self.SetAutoLayout(True)
        self.SetSizer(vbox)
        vbox.Fit(self)
        vbox.SetSizeHints(self)
        self.Layout()

        wx.EVT_BUTTON(self, wx.ID_OK, self.OnOK)
        wx.EVT_BUTTON(self, wx.ID_CANCEL, self.OnCancel)

    def OnOK(self, event):
        self.url = self.combo_value.GetValue()
        self.EndModal(wx.ID_OK)

    def OnCancel(self, event):
        self.EndModal(wx.ID_CANCEL)

def wms_dialog(context):
    """Request URL from user and add WMS Layer.

    context -- The Thuban context.
    """
    dialog = SelectWMSServer(context.mainwindow)

    if dialog.ShowModal() == wx.ID_OK:
        url = dialog.url
        if len(url) == 0:
            url = None
    else:
        url = None
    dialog.Destroy()

    if url is None:
        return

    wms_layer = WMSLayer('A WMS Layer', url)
    if wms_layer.error_msg is not None:
        context.mainwindow.RunMessageBox(_('WMS'), wms_layer.error_msg)

    map = context.mainwindow.canvas.Map()
    if map.projection is None:
        map.SetProjection(wms_layer.projection)
    has_layers = map.HasLayers()
    map.AddLayer(wms_layer)
    if not has_layers:
        # if we're adding a layer to an empty map, fit the
        # new map to the window
        context.mainwindow.canvas.FitMapToWindow()

wx.InitAllImageHandlers()
wms_extension = WMSExtension('WMS')

# register the new command
registry.Add(Command('wms', _('Add WMS layer ...'), wms_dialog,
                         helptext = _('Add a WMS Layer')))

# find the experimental menu (create it anew if not found)
experimental_menu = main_menu.FindOrInsertMenu('experimental',
                                               _('Experimenta&l'))

# finally add the new entry to the experimental menu
experimental_menu.InsertItem('wms')
