<?php
/**
 * Class represents records from table selfservice_type_resource
 * {autogenerated}
 * @property int $type_resource_id PK
 * @property int $resource_id
 * @property string|null $resource_type
 * @property int $type_id FK selfservice_type
 * @property int $value
 * {/autogenerated}
 */
class SelfserviceTypeResource extends Am_Record
{
}

/** @extends Am_Table<SelfserviceTypeResource> */
class SelfserviceTypeResourceTable extends Am_Table
{
    protected $_key = 'type_resource_id';
    protected $_table = '?_selfservice_type_resource';

    /**
     * @param ResourceAbstract $r
     * @return SelfserviceTypeResource
     */
    function getTypeResource(ResourceAbstract $r)
    {
        return $this->findFirstBy([
            'resource_type' => $r->getAccessType(),
            'resource_id' => $r->pk()
        ]);
    }

    /**
     * @param ResourceAbstract $r
     * @param int $value
     * @param int $type_id
     */
    function setTypeResource(ResourceAbstract $r, $value, $type_id)
    {
        if (!$tr = $this->getTypeResource($r)) {
            $tr = $this->createRecord();
            $tr->resource_id = $r->pk();
            $tr->resource_type = $r->getAccessType();
        }

        $tr->value = $value;
        $tr->type_id = $type_id;
        $tr->save();
    }

    function dropTypeResource(ResourceAbstract $r)
    {
        $this->deleteBy([
            'resource_type' => $r->getAccessType(),
            'resource_id' => $r->pk()
        ]);
    }
}