# Copyright (C) 2003, 2004 by Intevation GmbH
# Authors:
# 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.

This extension is in a very experimental stage!
It just demonstrates how to add a special
layer into Thuban via an extension.
Some things are not wired, so be prepared for Exceptions
everywhere.
"""

__version__ = "$Revision: 1.13 $"
# $Source: /thubanrepository/thuban/Extensions/wms/wms.py,v $
# $Id: wms.py,v 1.13 2005/04/26 15:04:22 joey Exp $

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

from wxPython.wx import *

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(layer, 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(wxDialog):

    ID_COMBOVALUE = 4003

    def __init__(self, parent):
        wxDialog.__init__(self, parent, -1, _("Select WMS Server"),
            style = wxDEFAULT_DIALOG_STYLE
                  | wxSYSTEM_MENU
                  | wxRESIZE_BORDER)

        self.combo_value = wxComboBox(self, self.ID_COMBOVALUE, size=(500,-1))
        self.combo_value.Append("")
        self.combo_value.Append('http://frida.intevation.org/cgi-bin/frida_wms?')
        #self.combo_value.Append('http://wms.jpl.nasa.gov/wms.cgi?')
        #self.combo_value.Append('http://eukrante.hq:9089/cgi-bin/wms_shg?')
        #self.combo_value.Append('http://131.220.106.112:8080/deegree0.7/wms?')
        #self.combo_value.Append('http://demo.cubewerx.com/demo/cubeserv/cubeserv.cgi?CONFIG=gita&')
        self.combo_value.SetSelection(0)

        button_ok = wxButton(self, wxID_OK, _("OK"))
        button_ok.SetDefault()
        button_close = wxButton(self, wxID_CANCEL, _("Close"))

        vbox = wxBoxSizer(wxVERTICAL)
        vbox.Add(self.combo_value, 1, wxEXPAND|wxALL|wxCB_SORT, 10)
        hbox = wxBoxSizer(wxHORIZONTAL)
        hbox.Add(button_ok, 0, wxALL, 10)
        hbox.Add(button_close, 0, wxALL, 10)
        vbox.Add(hbox, 0, 10)

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

        EVT_BUTTON(self, wxID_OK, self.OnOK)
        EVT_BUTTON(self, wxID_CANCEL, self.OnCancel)

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

    def OnCancel(self, event):
        self.EndModal(wxID_CANCEL)

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

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

    if dialog.ShowModal() == wxID_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()

wxInitAllImageHandlers()
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')
