<?php

namespace TdyAvatars\Model;

use TdyCommons\Filter\Word\LowercaseFirst;
use TdyCommons\Model\Model;
use TdySports\Model\Team;
use TdySports\Table\Leagues;
use TdySports\Table\Sports;
use TdySports\Table\Statuses;
use TdySports\Table\Teams;
use TdySports\Table\Weeks;
use Zend\Filter\FilterChain;
use Zend\Filter\Word\DashToCamelCase;
use Zend\Filter\Word\UnderscoreToCamelCase;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\ServiceManager;

/**
 * Class Mixture
 *
 * @package TdySports\Model
 *
 * @author  James Lloyd Atwil <james@nadows.com>
 */
class Avatar extends Model
{


    /**
     * The unique ID for Sport.
     *
     * @var int
     */
    public $id = 0;

    /**
     * @var string
     */
    public $name = '';

    /**
     * @var string
     */
    public $file = '';

    /**
     * @var string
     */
    public $path = '';

    /**
     * @var int
     */
    public $owner = 0;

    /**
     * @var null|ServiceManager|ServiceLocatorInterface
     */
    protected $sm;

    /**
     * @param null $data
     * @param null $sm
     */
    public function __construct($data = null, $sm = null)
    {
        $this->sm = $sm;

        if (!empty($data) && is_array($data)) {
            $this->exchangeArray($data);
        }

    }

    /**
     * @param null|ServiceManager|ServiceLocatorInterface $sm
     */
    public function setServiceLocator($sm)
    {
        $this->sm = $sm;

        $base       = $this->sm->get('Request')->getBasePath();
        $path       = $this->sm->get('config')['avatar']['dir'];
        $this->path = ($base != '' ? $base :  '/') . $path . $this->file;
    }

    /**
     * @see Model::exchangeArray()
     *
     * @param array $data
     */
    public function exchangeArray($data)
    {
        parent::exchangeArray($data);

        foreach ($data as $key => $value) {
            $filter = new FilterChain();
            if (strpos($key, '-') !== false) {
                $filter->attach(new DashToCamelCase());
            } else {
                $filter->attach(new UnderscoreToCamelCase());
            }

            $filter->attach(new LowercaseFirst());
            $nKey = $filter->filter($key);

            if (!property_exists(__CLASS__, $nKey)) {
                continue;
            } else {
                $inArray = in_array($nKey, ['id', 'owner']);
                if ($inArray) {
                    $this->$nKey = (int) $value;
                } else {
                    $this->$nKey = $value;
                }
            }
        }

        if (!is_null($this->sm)) {
            $path       = $this->sm->get('config')['avatars']['dir'];
            $this->path = $path . $this->file;
        }
    }

    /**
     * @return \StdClass
     */
    public function toStdClass()
    {
        $object = parent::toStdClass();

        if (is_null($this->sm)) {
            return $object;
        }

        return $object;
    }

}
