# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsVirtualLayerProvider

.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'Hugo Mercier'
__date__ = '26/01/2015'
__copyright__ = 'Copyright 2015, The QGIS Project'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

import qgis

from PyQt4.QtCore import *

from qgis.core import (QGis,
                       QgsVectorLayer,
                       QgsFeature,
                       QgsFeatureRequest,
                       QgsField,
                       QgsGeometry,
                       QgsPoint,
                       QgsMapLayerRegistry
                      )

from utilities import (getQgisTestApp,
                       TestCase,
                       unittest,
                       unitTestDataPath
                       )
QGISAPP, CANVAS, IFACE, PARENT = getQgisTestApp()

import os
import time

import pyspatialite.dbapi2 as db

class TestConnPool(TestCase):
    def test(self):
        # always use the same file
        fn = '/tmp/t.sqlite'

        for it in range(2):
            print it
            # make sure the file does not exist
            if os.path.exists(fn):
                os.unlink(fn)
            conn = db.connect(fn, isolation_level = None)
            # create a simple geometry table with 2 features
            cur = conn.cursor()
            cur.execute("BEGIN")
            cur.execute("SELECT InitSpatialMetadata()")
            cur.execute("CREATE TABLE t%d(id INTEGER PRIMARY KEY)" % it)
            cur.execute("SELECT AddGeometryColumn('t%d', 'geometry', 4326, 'POINT', 'XY')" % it)
            cur.execute("INSERT INTO t%d (id, geometry) VALUES(1, GeomFromText('POINT(0 0)', 4326))" % it)
            cur.execute("INSERT INTO t%d (id, geometry) VALUES(2, GeomFromText('POINT(1 1)', 4326))" % it)
            cur.execute("COMMIT")
            conn.close()

            l = QgsVectorLayer("dbname=%s table=t%d (geometry)" % (fn,it), "tt", "spatialite", False)
            assert l.isValid()
            QgsMapLayerRegistry.instance().addMapLayer(l)
            assert l.hasGeometryType()
            # iterate over features
            assert sum(f.id() for f in l.getFeatures()) == 3
            # => fails the second time it is executed : "no such table t1"

            QgsMapLayerRegistry.instance().removeMapLayer(l.id())

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

