<?php 

namespace HwapX\Core\Library\DB\SQL;

use F3;

class Mapper extends \DB\SQL\Mapper {
    protected $sizes = array();

	public function getMetadata($adhoc = false) {
		return $this->fields + ($adhoc ? $this->adhoc : array());
	}

    public function size($field = null) {
        if(!$this->sizes)
            $this->sizes = $this->parseSizes();

        if($field)
            return $this->sizes[$field];

        return $this->sizes;
    }

    protected function parseSizes($fields = null) {
        $result = array();
        if(!$fields)
            $fields = $this->schema();

        foreach ($fields as $fieldname => $field) {
            $size = 0;
            if(isset($field['type']) && preg_match('/(?<=char\()\d+(?=\))/i', $field['type'], $matches)) {
                $size = (int)$matches[0];
            }

            $result[$fieldname] = $size;
        }

        return $result;
    }

    /**
    *   Instantiate class
    *   @param $db object
    *   @param $table string
    *   @param $fields array|string
    *   @param $ttl int
    **/
    function __construct(\DB\SQL $db,$table,$fields=NULL,$ttl=null) {
        if($ttl === null) {
            $ttl = (int)\F3::instance()->get('SCHEMATTL') ?: 60;
        }

        parent::__construct($db, $table, $fields, $ttl);
    }
}