<?php

namespace domain\User\UserMessage;

use common\components\ActiveRecordCommon;
use domain\User\User\User;

class UserMessage extends ActiveRecordCommon
{
    public static function tableName()
    {
        return 'user_message';
    }

    public function rules()
    {
        return [
            [['id_user', 'message', 'created_at', 'created_by'], 'required'],
            [['message'], 'string'],
            [['id_user', 'created_by'], 'integer'],
            [['created_at', 'read_at'], 'safe']
        ];
    }

    public function attributeLabels()
    {
        return [
            'id_user' => 'Utilisateur',
            'message' => 'Message',
            'created_at' => 'Date de création',
            'created_by' => 'Créé par',
            'read_at', 'Date de lecture'
        ];
    }

    /* Getters / Setters */

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getUser(): User
    {
        return $this->userRelation;
    }

    public function setUser(User $user): self
    {
        $this->populateFieldObject('id_user', 'userRelation', $user);
        return $this;
    }

    public function getMessage(): string
    {
        return $this->message;
    }

    public function setMessage(string $message): self
    {
        $this->message = $message;
        return $this;
    }

    public function getCreatedAt(): \DateTime
    {
        return new \DateTime($this->created_at);
    }

    public function setCreatedAt(\DateTime $createdAt): self
    {
        $this->created_at = $createdAt->format('Y-m-d H:i:s');
        return $this;
    }

    public function getCreatedBy(): User
    {
        return $this->createdByRelation;
    }

    public function setCreatedBy(User $createdBy): self
    {
        $this->populateFieldObject('created_by', 'createdByRelation', $createdBy);
        return $this;
    }

    public function getReadAt(): ?\DateTime
    {
        if($this->read_at) {
            return new \DateTime($this->read_at);
        }

        return null;
    }

    public function setReadAt(\DateTime $readAt): self
    {
        $this->read_at = $readAt->format('Y-m-d H:i:s');
        return $this;
    }

    /* Relations */

    public function getUserRelation()
    {
        return $this->hasOne(User::class, ['id' => 'id_user']);
    }

    public function getCreatedByRelation()
    {
        return $this->hasOne(User::class, ['id' => 'created_by']);
    }
}