<?php

namespace ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Interfaces;


/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 05.09.19
 * Time: 13:34
 * Class AbstractModel
 */
abstract class AbstractModel
{
    /**
     * @description storage other resources
     * @var array
     */
    protected $resources = [];

    /**
     * AbstractModel constructor.
     * @param array $data
     */
    public function __construct($data = [])
    {
        $this->fill($data);
    }

    /**
     * @param array $data
     * @return $this
     */
    public function fill($data = [])
    {

        foreach ($data as $key => $row)
        {
            $property = strtolower($key);
            /* method Name */
            $method = 'set' . ucfirst($property);
            /* property name */
            if (method_exists($this, $method)) {
                /**
                 * set through method if exists
                 *
                 */
                $this->$method($row);

            } elseif (property_exists($this, $property)) {
                /**
                 * set as property if exists
                 */
                $this->{$property} = $row;
            } else {
                /**
                 * add data to resources if property or methods doesnt exists
                 */
                $this->addResource($property, $row);
            }

        }

        return $this;
    }

    /**
     * @param $name
     * @return |null
     */
    public function getDataResourceA($name)
    {
        foreach ($this->resources['a'] as $res) {
            if ($res['N'] === $name) {
                return $res['DATA'];
            }
        }

        return null;
    }

    /**
     * @param $name
     * @return array
     */
    public function getDataResourceACollection($name)
    {
        foreach ($this->resources['a'] as $res) {
            if ($res['N'] === $name) {
                $tmp[] = $res['DATA'];
            }
        }

        return $tmp;
    }

    /**
     * @return mixed
     */
    public function getAllDataResourcesAAttributes()
    {
        foreach ($this->resources['a'] as $res) {
            $tmp[$res['N']] = $res['DATA'];

        }

        return $tmp;
    }

    /**
     * @param $key
     * @param array $data
     * @return $this
     */
    public function addResource($key, $data = [])
    {
        $this->resources[$key] = $data;
        return $this;
    }

}