<?php

namespace Ignite\Core\Entities;

use Ignite\Core\Collections\PermissionsCollection;

class Permission extends Base
{
    const ACTIVE = 1;
    const INACTIVE = 0;

    /**
     * The custom table name.
     * @var string
     */
    protected $table = 'core_permission';

    /**
     * @var array
     */
    protected $casts = [
        'is_user_defined' => 'bool',
    ];

    /**
     * Eloquent event listeners.
     */
    public static function boot()
    {
        parent::boot();
        static::saving(function (Permission $model) {
            if (empty($model->status)) {
                $model->status = static::ACTIVE;
            }
        });
        static::saved(function () {
            app('authorization')->forgetPermissions()->registerPermissions();
        });
        static::deleting(function (Permission $model) {
            if (! $model->isUserDefined()) {
                throw new \Exception('You cannot delete a system defined user permission.');
            }
        });
    }

    /**
     * The relationship to the permission group.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function groups()
    {
        return $this->belongsToMany(Group::class, 'core_group_permission', 'permission_id', 'group_id')->withTimestamps();
    }

    /**
     * Create a new Eloquent Collection instance.
     *
     * @param array $models
     * @return \Ignite\Core\Collections\PermissionsCollection
     */
    public function newCollection(array $models = [])
    {
        return new PermissionsCollection($models);
    }

    /**
     * Determine if the group is user-defined.
     *
     * @return bool
     */
    public function isUserDefined()
    {
        return (bool)$this->is_user_defined;
    }

    /**
     * Determine if the group is active.
     *
     * @return bool
     */
    public function isActive()
    {
        return $this->status === static::ACTIVE;
    }

    /**
     * Determine if the group is inactive.
     *
     * @return bool
     */
    public function isInactive()
    {
        return $this->status === static::INACTIVE;
    }
}
