<?php

namespace App\Models;

use File;
use Illuminate\Database\Eloquent\Model;

use App\Repositories\MessageRepository;
use App\Http\Traits\FcmNotification;
use App\Http\Traits\CustomerId;

/**
 * Class Message
 *
 * @package App\Models
 */
class Message extends Model
{

    use CustomerId;

    /**
     * The root directory where message files are stored
     */
    const ROOT_STORAGE_FILES = 'messages_files/';
    /**
     * The group directory where message files are stored
     */
    const GROUP_DIRECTORY_PREFIX = 'group_';

    /**
     * The table field that stores the primary key.
     *
     * @var string
     */
    protected $primaryKey = 'oid';

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'messages';

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = true;

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'useroid' => 'integer',
        'groupoid' => 'integer'
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [ 'useroid', 'groupoid', 'text', 'file' ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [ 'pivot' ];

    /**
     * Boot message
     */
    public static function boot()
    {
        parent::boot();

        Message::created(function ($message) {
            FcmNotification::pushNotification($message);
        });
    }

    /**
     * The user that sent the message
     *
     * @return User|\Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo('App\Models\User', 'useroid', 'oid');
    }

    /**
     * The group in which the message was sent
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function group()
    {
        return $this->belongsTo('App\Models\Group', 'groupoid', 'oid');
    }

    /**
     * Message repository
     *
     * @return \App\Repositories\MessageRepository
     */
    public function repository()
    {
        return MessageRepository::instance($this);
    }

    /**
     * Get group directory where files are saved
     *
     * @param int   $groupId
     * @param mixed $customerId
     * @return string
     */
    public static function getGroupDirPath($groupId, $customerId = null)
    {
        $customerId = CustomerId::getCustomerId() ? CustomerId::getCustomerId() : $customerId;

        return self::ROOT_STORAGE_FILES . $customerId . '/' . self::GROUP_DIRECTORY_PREFIX . $groupId;
    }

    /**
     * Get a files public url
     *
     * @return \Illuminate\Contracts\Routing\UrlGenerator|string
     */
    public function getFilePublicUrl()
    {
        $filePublicUrl = '';
        $filename = self::getGroupDirPath($this->group->oid) . '/' . $this->file;

        if ($this->file && File::exists($filename)) {
            $filePublicUrl = url($filename);
        }

        return $filePublicUrl;
    }

    /**
     * Get message smaller image
     *
     * @param array $params
     * @return string
     */
    public function getSmallerImage(array $params = [])
    {
        $filename = self::getGroupDirPath($this->group->oid) . '/' . $this->file;
        $sendParams = [
            'customerid' => CustomerId::getCustomerId(),
            'group'      => $this->group->oid,
            'height'     => $params['height'],
            'filename'   => $this->file
        ];

        return ($this->file && File::exists($filename) && (@is_array(getimagesize($filename)))) ? route('apiMessageSmallerImage', $sendParams) : '';
    }

    /**
     * The info outputted on API calls
     *
     * @param array
     * @return array
     */
    public function apiOutputData($extra = [])
    {
        $data = [
            'id'                => $this->oid,
            'text'              => $this->text,
            'file'              => $this->getFilePublicUrl(),
            'original_filename' => $this->file_original_name,
            'smaller_image'     => $this->getSmallerImage([ 'height' => 90 ]),
            'timestamp'         => $this->created_at,
            'created_at'        => $this->created_at->getTimestamp(),
            'userid'            => $this->user->oid,
            'user_name'         => $this->user->fullname(),
            'user_picture'      => $this->user->getAvatar([ 'customerid' => request()->header('CustomerID'), 'width' => 40, 'height' => 40 ]),
            'groupid'           => $this->group->oid
        ];

        return array_merge($data, $extra);
    }
}