#!/usr/bin/env python
# encoding: utf-8
#
# ** header v3.0
# This file is a part of the CaosDB Project.
#
# Copyright (C) 2020 Indiscale GmbH <info@indiscale.com>
# Copyright (C) 2020 Florian Spreckelsen <f.spreckelsen@indiscale.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# ** end header

import os
import unittest
from tempfile import NamedTemporaryFile

import caosdb as db
from caosadvancedtools.cache import UpdateCache


class CacheTest(unittest.TestCase):
    def empty_db(self):
        try:
            db.execute_query("FIND Test*").delete()
        except Exception:
            pass

    def setUp(self):
        self.cache = NamedTemporaryFile(delete=False).name
        os.remove(self.cache)
        self.empty_db()

    def tearDown(self):
        self.empty_db()
        os.remove(self.cache)

    def test_same_old_different_new(self):
        """Formerly, inserting two containers with different changes to the
        same entity into the update cache would result in an
        IntegrityException.

        """
        rt = db.RecordType(name="TestType").insert()
        db.Property(name="TestProp1", datatype=db.TEXT).insert()
        db.Property(name="TestProp2", datatype=db.TEXT).insert()
        rec = db.Record(name="TestRecord").add_parent(rt).insert()

        # add TestProp1 to TestRecord
        rec.add_property(name="TestProp1", value="blub")
        cont = db.Container().append(rec)

        update = UpdateCache(db_file=self.cache)
        run_id = "a"
        update.insert(cont, run_id)
        assert len(update.get_updates(run_id)) == 1

        # duplicate and add TestProp2 to TestRecord
        rec = db.execute_query("FIND Record TestRecord", unique=True)
        rec.add_property(name="TestProp2", value="bla")
        cont = db.Container().append(rec)
        # same old digest, different new digest
        update.insert(cont, run_id)
        assert len(update.get_updates(run_id)) == 2
