<?php
namespace SabaiApps\Directories\Component\Entity\Helper;

use SabaiApps\Directories\Application;

class FieldCacheHelper
{   
    public function help(Application $application, array $entities)
    {
        $platform = $application->getPlatform();
        $loaded = [];
        foreach (array_keys($entities) as $entity_key) {
            $entity = $entities[$entity_key];
            if ($cache = $platform->getCache('_entity_field_' . $entity->getBundleName() . '__' . $entity->getId(), 'entity_field')) {
                $entity->initFields($cache[0], $cache[1]);
                $loaded[$entity->getId()] = $entity->getId();
            }
        }
        return $loaded;
    }
    
    public function save(Application $application, array $entities)
    {
        $platform = $application->getPlatform();
        foreach (array_keys($entities) as $entity_key) {
            $entity = $entities[$entity_key];
            $platform->setCache(
                array($entity->getFieldValues(), $entity->getFieldTypes()),
                '_entity_field_' . $entity->getBundleName() . '__' . $entity->getId(),
                null,
                'entity_field'
             );
        }
    }

    public function remove(Application $application, $bundleName, array $entityIds)
    {
        $platform = $application->getPlatform();
        foreach ($entityIds as $entity_id) {
            $platform->deleteCache('_entity_field_' . $bundleName . '__' . $entity_id, 'entity_field');
        }
    }

    public function clean(Application $application, $bundleName = null)
    {
        $application->getPlatform()->clearCache('entity_field');
    }
}