<?php

/**
 * CGBetterUploads API
 *
 * @package CGBetterUploads
 */

namespace CGBetterUploads;

/**
 * A class to represent the information about the download of a file.
 *
 * @property-read int $id The unique id of this download
 * @property-read string $file_guid The unique guid of the file downloaded
 * @property-read string $ip The ip address of the user that downloaded the file
 * @property-read int $date The unix timestamp when the file download completed.
 * @property-read int $feu_user The FEU-uid of the user that downloaded the file, if the user was logged in to the FEU module.
 */
class Download
{
    /**
     * @ignore
     */
    private $_data = [ 'id'=>null, 'file_guid'=>null, 'date'=>null, 'ip'=>null, 'feu_user'=>null ];

    /**
     * @ignore
     */
    protected function __construct() {}

    /**
     * @ignore
     */
    public function __get( string $key )
    {
        switch( $key ) {
        case 'file_guid':
        case 'ip':
            if( !is_null($this->_data[$key]) ) return trim($this->_data[$key]);
            return;

        case 'id':
        case 'date':
        case 'feu_user':
            if( !is_null($this->_data[$key]) ) return (int) $this->_data[$key];
            return;

        default:
            throw new \LogicException("$key is not a gettable member of ".__CLASS__);
        }
    }

    /**
     * @ignore
     */
    public function __set( string $key, $val )
    {
        throw new \LogicException("$key is not a settable member of ".__CLASS__);
    }

    /**
     * Convert this object to an array.
     *
     * @internal
     * @return array
     */
    public function to_array() : array
    {
        return $this->_data;
    }

    /**
     * Construct a download object from an array.
     *
     * @param array $in
     * @return Download
     */
    public static function from_array( array $in ) : Download
    {
        $obj = new self;
        foreach( $in as $key => $val ) {
            switch( $key ) {
            case 'id':
            case 'date':
            case 'feu_user':
                if( !is_null($val) ) $obj->_data[$key] = (int) $val;
                break;
            case 'file_guid':
            case 'ip':
                if( !is_null($val) ) $obj->_data[$key] = trim($val);
                break;
            }
        }
        return $obj;
    }
} // class
