<?php
/**
 * Created by PhpStorm.
 * User: brian
 * Date: 4/2/19
 * Time: 10:19 AM
 */

namespace Hilco\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * Trait HasModelTranslations
 * @package Hilco\Models
 */
trait HasModelTranslations {

    protected $queuedTranslations = [];

    public static function bootHasModelTranslations() {
        static::created (function (Model $translatableModel) {
            foreach ($translatableModel->queuedTranslations as $translationInfo) {
                $translatableModel->setTranslation($translationInfo['language'], $translationInfo['column_name'], $translationInfo['translation']);
            }
            $translatableModel->queuedTranslations = [];
        });
    }

    public function translations() {
        return $this->morphMany(WebModelTranslation::class, 'translatable');
    }


    // The regular getTranslation function returns empty string instead of default probably to please some Germans or something stupid
    public function getTranslationWithDefaultForReal ($columnName, $language = false, $default = false) {
        if ($default === false) $default = \Illuminate\Support\Arr::get($this->attributes, $columnName, '');

        if(config('hilco.hasTranslations') != 'DISABLED') {
            if ($language === false) $language = b2b()->activeLanguage();
            $modelTranslation = $this->translations->where('language', $language)->where('column_name', $columnName)->first();
            if (!isset($modelTranslation) && $language != AvailableLanguage::DEFAULT_LANG_CODE) {
                return $default;
            }
            return \Illuminate\Support\Arr::get($modelTranslation, "translation", $default);
        }

        return $default;
    }

    public function getTranslation ($columnName, $language = false, $default = false) {
        if ($default === false) $default = \Illuminate\Support\Arr::get($this->attributes, $columnName, '');

        if(config('hilco.hasTranslations') != 'DISABLED') {
            if ($language === false) $language = b2b()->activeLanguage();
            $modelTranslation = $this->translations->where('language', $language)->where('column_name', $columnName)->first();
            if (!isset($modelTranslation) && $language != AvailableLanguage::DEFAULT_LANG_CODE) {
                // If you don't want to get an empty string in your translation and instead want the default use getTranslationWithDefaultForReal above
                return '';
            }
            return \Illuminate\Support\Arr::get($modelTranslation, "translation", $default);
        }

        return $default;
    }

    public function getTranslationForEdit ($columnName, $language = false, $default = false) {
        if ($language === false) $language = b2b()->activeLanguage();
        if ($default === false) {
            $default = $columnName . "_for_edit";
        }
        $modelTranslation = $this->translations->where('language', $language)->where('column_name', $columnName)->first();
        if (!isset($modelTranslation) && $language != AvailableLanguage::DEFAULT_LANG_CODE) {
            return '';
        }
        return isset($modelTranslation) ? $modelTranslation->translation_for_edit : $this->$default;
    }

    public function deleteTranslation($columnName, $language){
        $this->translations->where('language', $language)->where('column_name', $columnName)->first()->delete();
    }

    public function setTranslation($language, $columnName, $translation, $type = null) {
        if (!$this->exists) {
            $this->queuedTranslations[] = [
                'language' => $language,
                'column_name' => $columnName,
                'translation' => $translation
            ];
        } else {
            $modelTranslation = $this->translations()->withTrashed()->where('language', $language)->where('column_name', $columnName)->first();
            if(!empty($modelTranslation)){
                $modelTranslation->restore();
            }
            if(is_null($type)){
                $type = lcfirst(class_basename($this));
            }
            $this->translations()
                ->updateOrCreate(
                    [
                        'language' => $language,
                        'column_name' => $columnName
                    ],
                    [
                        'translatable_type' => $type,
                        'translation' => $translation
                    ]
                )
            ;
        }
    }

    protected static $morphMap = [
        'feedBackSubject'   => FeedbackSubject::class,
        'feedBackType'      => FeedbackType::class,
        'webAttribute'      => WebAttribute::class,
        'webAttributeValue' => WebAttribute_WebPart::class,
        'webContactBlock'   => WebContactBlock::class,
        'webLink'           => WebLink::class,
        'webLinkCategory'   => WebLinkCategory::class,
        'webPart'           => WebPart::class,
        'webFamily'         => WebFamily::class,
        'webCategory'       => WebCategory::class,
        'webCollection'     => WebCollection::class,
        'webGroup'          => WebGroup::class,
        'webSilo'           => WebSilo::class,
        'webSiloOverride'   => WebSiloOverride::class,
        'assetable'         => Assetable::class,
        'datafeedField'     => DatafeedField::class,
    ];

    /**
     * Get the morph mapping of trigger/action types to their actual class models
     * @return array
     */
    public static function getMorphMap() {
        return self::$morphMap;
    }
}