<?php

    namespace Icing\Controller\Component;

    use Cake\Core\Configure;
    use Cake\Datasource\EntityInterface;
    use Cake\Utility\Hash;
    use Cake\Utility\Inflector;

    class FlashComponent extends \Cake\Controller\Component\FlashComponent
    {

        public function __call(string $name, array $args): void
        {
            if ($this->getController()->getRequest()->is(['json', 'ajax'])) {
                return;
            }
            $args[1]['plugin'] = $args[1]['plugin'] ?? 'Icing';
            parent::__call($name, $args);
        }

        public function entityError(EntityInterface $entity, $limit = 2): void
        {
            if ($entity->hasErrors()) {
                $errors = Hash::flatten($entity->getErrors());
                foreach ($errors as $field => $error) {
                    if ($limit-- <= 0) return;

                    $field = array_slice(explode('.', $field), -2, 1)[0] ?? 'error';
                    if (strtolower($field) !== 'error') {
                        $error = Inflector::humanize($field) . ': ' . $error;
                    }
                    $this->error($error);
                }
            }
        }


    }
