<?php

namespace App;

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

class Language extends Model
{
    protected $fillable = ['locale', 'name'];

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

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

        static::created($createLanguage);
    }

    /**
     *  Each language may have several translations.
     */
    public function translations()
    {
        return $this->hasMany(Translation::class, 'locale', 'locale');
    }

    /**
     *  Returns the name of this language in the current selected language.
     *
     *  @return string
     */
    public function getLanguageLocaleAttribute()
    {
        return "languages.{$this->locale}";
    }

    public function scopeGetGroupTemplate($query)
    {
        if ( $query->whereLocale('en')->get()->isNotEmpty() ) {
            $translations = $query->whereLocale('en')
                                ->first()
                                ->translations()
                                ->whereNotIn('group', ['validation', 'auth', 'passwords'])
                                ->get();
            $translations = $translations->mapToGroups(function($item) {
                return [$item['group'] => $item['item']];
            })->toArray();

            return $translations;
        }

        return false;
    }

    public function createLanguage()
    {
        if ( $this->getGroupTemplate() ) {
            foreach ($this->getGroupTemplate() as $group => $value) {
                foreach ($value as $key) {
                    $this->translations()->create([
                        'group' => $group,
                        'item' => $key
                    ]);
                }
            }
        }
    }

    public static function getGroup(string $group, string $locale)
    {
        return Cache::rememberForever(static::getCacheKey($group, $locale), function () use ($group, $locale) {
            $lang = static::query()
                ->whereLocale($locale)->first();

            if(! $lang ){
                $lang = static::query()
                    ->whereLocale(get_default_language())->first();
            }

            $trans = $lang->translations()->whereGroup($group)
                ->pluck('text', 'item')
                ->toArray() ?? [];

            return $trans;
        });
    }

    public static function getCacheKey(string $group, string $locale)
    {
        return "mopie.translation.{$group}.{$locale}";
    }
}
