<?php

namespace TdyGames\InputFilter;

use TdyCommons\InputFilter\BaseInputFilter;
use Zend\InputFilter\Factory as InputFilterFactory;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Validator;

/**
 * Class Attribute
 *
 * @package TdyAttributes\InputFilter
 *
 * @author  James Lloyd Atwil <james@nadows.com>
 */
class Attribute extends BaseInputFilter
{

    /**
     * @param ServiceLocatorInterface $sm
     * @param bool                    $isEdit
     */
    public function __construct($sm, $isEdit = false)
    {
        $this->sm = $sm;

        $factory = new InputFilterFactory();

        $this->add($factory->createInput([
            'name'     => 'id',
            'required' => false,
            'filters'  => $this->filterStrings(),
        ]));

        $this->add($factory->createInput([
            'name'       => 'key',
            'required'   => true,
            'filters'    => $this->filterStrings(),
            'validators' => [
                $this->validateNotEmpty('Attribute key is required.'),
                [
                    'name'    => '\Zend\Validator\Db\NoRecordExists',
                    'options' => [
                        'adapter'                => $this->sm->get('db-01'),
                        'table'                  => $this->sm->get('Config')['mappings']['views']['game_attributes_active']['name'],
                        'field'                  => $this->sm->get('Config')['mappings']['views']['game_attributes_active']['columns']['key'],
                        'exclude'                => [
                            'field' => $this->sm->get('Config')['mappings']['views']['game_attributes_active']['columns']['id'],
                            'value' => $this->data['id']
                        ],
                        'encoding'               => 'UTF-8',
                        'messages'               => [
                            Validator\Db\NoRecordExists::ERROR_RECORD_FOUND => 'Key is already taken.'
                        ],
                        'break_chain_on_failure' => true,
                    ],
                ],
            ],
        ]));

        $this->add($factory->createInput([
            'name'       => 'name',
            'required'   => true,
            'filters'    => $this->filterStrings(),
            'validators' => [
                $this->validateNotEmpty('Attribute name is required.')
            ],
        ]));

        $this->add($factory->createInput([
            'name'       => 'value',
            'required'   => true,
            'filters'    => $this->filterStrings(),
            'validators' => [
                $this->validateNotEmpty('Attribute default value is required.')
            ],
        ]));

    }

}