<?php

namespace AuthStack\TwoFactor\Model;

class Key implements KeyInterface
{
    protected $data = [];

    /**
     * @param array $data
     *
     * @return static
     */
    public static function fromArray(array $data)
    {
        static::check($data);

        $me = new static;

        $me->data = $data;

        return $me;
    }


    /**
     * @param array $array
     *
     * @return bool
     */
    protected static function check(array $array)
    {
        return true;
    }


    /**
     * @return int
     */
    public function getID()
    {
        return $this->fromData('id');
    }


    /**
     * @return bool
     */
    public function isU2F()
    {
        return $this->fromData('is_u2f', false);
    }


    /**
     * @return string
     */
    public function getTitle()
    {
        return $this->fromData('title', 'N/A');
    }


    /**
     * @return string
     */
    public function getType()
    {
        return $this->fromData('type', 'N/A');
    }


    /**
     * @return string
     */
    public function getCreatedAt()
    {
        return $this->fromData('created_at', 0);
    }


    /**
     * @return string
     */
    public function getUsedAt()
    {
        return $this->fromData('used_at', 0);
    }

    /**
     * @return array
     */
    public function toArray($show_secret_fields = false)
    {
        $result = [
            'id'            => $this->getID(),
            'title'         => $this->getTitle(),
            'type'          => $this->getType(),
            'created_at'    => $this->getCreatedAt(),
            'used_at'       => $this->getUsedAt()
        ];

        if($show_secret_fields)
        {
            $result = array_merge($result, [
                'secret_key' => $this->fromData('secret_key'),
                'qr' => $this->fromData('qr')
            ]);

        }

        return $result;
    }

    /**
     * @param string $key
     * @param null   $default
     *
     * @return null
     */
    protected function fromData($key = '', $default = null)
    {
        return isset($this->data[$key]) ? $this->data[$key] : $default;
    }
}