<?php

namespace App;

use Illuminate\Support\Facades\Cache;
use Illuminate\Database\Eloquent\Model;

class Translation extends Model
{
    protected $fillable = ['locale', 'namespace', 'group', 'item', 'text', 'unstable'];

    public static function boot()
    {
        parent::boot();

        $flushGroupCache = function (self $languageLine) {
            $languageLine->flushGroupCache();
        };

        static::saved($flushGroupCache);
        static::deleted($flushGroupCache);
    }

    public function flushGroupCache()
    {
        foreach (Language::all()->pluck('locale') as $locale) {
            Cache::forget(Language::getCacheKey($this->group, $locale));
        }
    }

    public function language()
    {
        return $this->belongsTo(Language::class, 'locale', 'locale');
    }

    public function getCodeAttribute()
    {
        return $this->namespace === '*' ? "{$this->group}.{$this->item}" : "{$this->namespace}::{$this->group}.{$this->item}";
    }

    public function flagAsReviewed()
    {
        $this->unstable = 0;
    }

    public function lock()
    {
        $this->locked = 1;
    }

    public function isLocked()
    {
        return (boolean) $this->locked;
    }

}
