# Copyright (c) 2008 by Intevation GmbH
# Authors:
# Anthony Lenton <anthony@except.com.ar>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with Thuban for details.

""" This module allows you to save your data as png files to be served as a
    Google Maps layer overlay. """

import os
import wx

if __name__ != '__main__':
    from Thuban.UI.command import registry, Command
    from Thuban import _
    from Thuban.UI.mainwindow import main_menu
    from Thuban.UI import internal_from_wxstring

from exporter import export

DEFAULT_DESTINATION_FOLDER = os.path.join (os.getcwd(), "tiles")

class exportGMapTilesDialog(wx.Dialog):
    def __init__(self, parent, ID, title,
                 pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=wx.DEFAULT_DIALOG_STYLE):
                     
        # initialize the Dialog
        wx.Dialog.__init__(self, parent, ID, title, pos, size, style)

        # Destination folder
        box_folder = wx.BoxSizer(wx.HORIZONTAL)
        box_folder.Add(wx.StaticText(self, -1, _("Destination folder:")), 1,
                     wx.ALL|wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL, 4)
        self.text_folder = wx.TextCtrl(self, -1, DEFAULT_DESTINATION_FOLDER)
        box_folder.Add(self.text_folder, 2, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
        self.button_folder = wx.Button (self, -1, _("Choose folder"))
        self.button_folder.Bind (wx.EVT_BUTTON, self.OnChooseFolder)
        box_folder.Add(self.button_folder, 1,wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)

        # Zoom levels
        box_zoom = wx.BoxSizer (wx.HORIZONTAL)
        box_zoom.Add (wx.StaticText (self, -1, _("Minimum Zoom:")), 0,
                      wx.ALL|wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL, 4)
        self.minZoomSpin = wx.SpinCtrl (self, size=(60, -1), min=1, max=17)
        self.Bind(wx.EVT_SPINCTRL, self.OnMinZoomChanged, self.minZoomSpin)
        box_zoom.Add (self.minZoomSpin, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)
        box_zoom.Add (wx.StaticText (self, -1, _("Maximum Zoom:")), 0,
                      wx.ALL|wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL, 4)
        self.maxZoomSpin = wx.SpinCtrl (self, size=(60, -1), min=1, max=17)
        self.Bind(wx.EVT_SPINCTRL, self.OnMaxZoomChanged, self.maxZoomSpin)
        box_zoom.Add (self.maxZoomSpin, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 4)

        #buttons
        box_buttons = wx.BoxSizer(wx.HORIZONTAL)
        button = wx.Button(self, wx.ID_OK, _("OK"))
        box_buttons.Add(button, 0, wx.ALL, 5)
        button = wx.Button(self, wx.ID_CANCEL, _("Cancel"))
        box_buttons.Add(button, 0, wx.ALL, 5)
        #set the button funcitons
        self.Bind(wx.EVT_BUTTON, self.OnOK, id=wx.ID_OK)
        self.Bind(wx.EVT_BUTTON, self.OnCancel, id=wx.ID_CANCEL)
      
        # compose the final dialog
        top = wx.BoxSizer(wx.VERTICAL)
        top.Add(box_folder, 0, wx.EXPAND |wx.ALL, 5)
        top.Add(box_zoom, 0, wx.EXPAND |wx.ALL, 5)
        top.Add(box_buttons, 0, wx.ALIGN_RIGHT)
        
        # final layout settings
        self.SetSizer(top)
        top.Fit(self)

    def OnMinZoomChanged (self, event):
        if self.maxZoomSpin.GetValue() < self.minZoomSpin.GetValue():
            self.maxZoomSpin.SetValue(self.minZoomSpin.GetValue())

    def OnMaxZoomChanged(self, event):
        if self.minZoomSpin.GetValue() > self.maxZoomSpin.GetValue():
            self.minZoomSpin.SetValue(self.maxZoomSpin.GetValue())

    def OnChooseFolder (self, event):
        dlg = wx.DirDialog(self, _("Select a folder to save the tiles in"), ".")
        if dlg.ShowModal() == wx.ID_OK:
            pfm_filename = internal_from_wxstring(dlg.GetPath())
            self.text_folder.ChangeValue (pfm_filename)
        dlg.Destroy()

    def RunDialog(self):
        self.ShowModal()
        self.Destroy()

    def endDialog(self, result):
        self.result = result
        if self.result is not None:
            self.EndModal(wx.ID_OK)
        else:
            self.EndModal(wx.ID_CANCEL)
        self.Show(False)

    def OnOK(self, event):
        self.result = "OK"
        self.dataFolder = self.text_folder.GetValue()
        self.minZoom = self.minZoomSpin.GetValue()
        self.maxZoom = self.maxZoomSpin.GetValue()
        self.endDialog(self.result)

    def OnCancel(self, event):
        self.endDialog(None)


def export_gmap_dialog(context):
    """ Select the destination folder and zoom levels needed.

    context -- The Thuban context.
    """
    dlg = exportGMapTilesDialog(context.mainwindow, -1,
                       _("Export Google Maps tiles"))
    dlg.RunDialog()
    if dlg.result == "OK":
        export (context, dlg.minZoom, dlg.maxZoom, dlg.dataFolder)

# register the new command
registry.Add(Command('export-gmaptiles', _("(experimental) ") + _('Export GMap Tiles'),
                     export_gmap_dialog, helptext=_('Export as Google Map tiles')))

# find the extension menu (create it anew if not found)
extensions_menu = main_menu.FindOrInsertMenu('extensions',
                                               _('E&xtensions'))

# finally add the new entry to the menu
extensions_menu.InsertItem('export-gmaptiles')

