<?php

  require_once ANGIE_PATH . '/tests/testdataobject/BaseTestDataObject.class.php';
  require_once ANGIE_PATH . '/tests/testdataobject/BaseTestDataObjects.class.php';
  require_once ANGIE_PATH . '/tests/testdataobject/TestDataObject.class.php';
  require_once ANGIE_PATH . '/tests/testdataobject/TestDataObjects.class.php';
  
//  define('USE_CACHE', true);

  class TestDataObjectCaching extends UnitTestCase {
    
    /**
     * Cache instance
     *
     * @var Cache
     */
    var $cache;
    
    function __construct($label = null) {
      parent::__construct('Test data object caching');
      
      $this->cache =& Cache::instance();
      $this->cache->useBackend('FileCacheBackend');
      $this->cache->backend->setCacheDir(TESTS_PATH . '/support/cache');
    } // TestDataObjectCaching
  
    function setUp() {
      DB::execute("CREATE TABLE " . TABLE_PREFIX . "test_data_objects (
        id int(10) unsigned NOT NULL auto_increment,
        name varchar(100) NOT NULL,
        description text,
        type enum('Task','Milestone','Message','File') NOT NULL default 'File',
        created_on datetime NULL,
        updated_on datetime NULL,
        PRIMARY KEY  (id)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
    } // setUp
    
    function tearDown() {
      DB::execute("DROP TABLE IF EXISTS " . TABLE_PREFIX . "test_data_objects");
      $this->cache->backend->clear();
    } // tearDown
    
    function testUpdate() {
      $object = new TestDataObject();
      $object->setName('Name');
      $object->save();
      
      $this->assertFalse(is_file($this->cache->backend->getFilePath(TABLE_PREFIX . 'test_data_objects_id_' . $object->getId())));
      
      $loaded_object = TestDataObjects::findById($object->getId());
      
      // We need to save cache before we can see if file is set
      $this->cache->backend->save();
      
      $this->assertTrue(is_file($this->cache->backend->getFilePath(TABLE_PREFIX . 'test_data_objects_id_' . $object->getId())));
      
      $loaded_object->setName('New name');
      $loaded_object->save();
      $this->assertFalse(is_file($this->cache->backend->getFilePath(TABLE_PREFIX . 'test_data_objects_id_' . $object->getId())));
      
      $loaded_again_object = TestDataObjects::findById($object->getId());
      $loaded_again_object->delete();
      $this->assertFalse(is_file($this->cache->backend->getFilePath(TABLE_PREFIX . 'test_data_objects_id_' . $object->getId())));
      
      $this->cache->backend->clear();
      
      $empty = true;
      $d = dir(TESTS_PATH . '/support/cache');
      while(($entry = $d->read()) !== false) {
        if(str_starts_with($entry, '.')) {
          continue;
        } // if
        $empty = false;
      } // if
      
      $this->assertTrue($empty);
    } // testUpdate
  
  } // TestDataObjectCaching

?>