import unittest
import os, sys
from Thuban.Model.layer import Layer
from Thuban.Model.map import Map
from Thuban.Model.session import Session
from Thuban.UI.context import Context
from Thuban.Lib.connector import ConnectorError

mapscriptAvailable=True
try:
    import mapscript
    from Extensions.gMapTiles.exporter import export
except ImportError:
    mapscriptAvailable=False

def rm_rf(d):
    for path in (os.path.join(d,f) for f in os.listdir(d)):
        if os.path.isdir(path):
            rm_rf(path)
        else:
            os.unlink(path)
    os.rmdir(d)

class DummyMainWindow(object):
    def __init__(self, canvas):
        self.canvas = canvas

class DummyCanvas(object):
    def __init__(self, map):
        self.map = map
    def Map(self):
        return self.map
    def VisibleExtent (self):
        return self.map.BoundingBox()

class TestGMapTileExport(unittest.TestCase):
    def setUp(self):
        self.session = Session("A Session")
        self.map = Map("A Map")
        self.session.AddMap(self.map)
        shapefile = "../../../Data/iceland/political.shp"
        self.store = self.session.OpenShapefile(shapefile)
        layer = Layer("A Layer", self.store)
        self.map.AddLayer(layer)

    def testExport(self):
        tileDir = 'temp'
        if not mapscriptAvailable:
            #Skip test...
            return
        mainwindow = DummyMainWindow(DummyCanvas(self.map))
        context = Context(None, self.session, mainwindow)
        export (context, 7, 7, tileDir)
        self.session.Destroy()
        rm_rf(tileDir)

if __name__ == "__main__":
    unittest.main()

