<?php namespace Concore\Foundation\Models\Traits;

use URL, Route, Config;

trait IdentifiableTrait {

	public function getNameAttribute() {
        if(!isset($this->name_field) || !$this->name_field) {
            $name_field = 'name';
        } else {
            $name_field = $this->name_field;
        }
		if(isset($this->attributes[$name_field])) {
			return $this->attributes[$name_field];
		} else {
			return ucwords($this->getHumanReadable()) . (isset($this->id) && $this->id ? ' #' . $this->id : '');
		}
	}

	public function getSnake() {
		return snake_case(class_basename(get_class($this)));
	}

	public function getSnakePlural() {
		return str_plural($this->getSnake());
	}

	public function getHumanReadable() {
		return str_replace('_',' ',$this->getSnake());
	}

	public function getHumanReadablePlural() {
		return str_plural($this->getHumanReadable());
	}

	public function getSlugged() {
		return str_replace('_','-',$this->getSnake());
	}

	public function getSluggedPlural() {
		return str_plural($this->getSlugged());
	}

	public function getUrl()
    {
        if (! setting_or_config('foundation.get-url-use-back-end-routes')) {
            if(Route::has($this->getSlugged())) {
                return URL::to(route($this->getSlugged(), $this->key));
            }
        } else {
            return URL::to(route('sculpt.show', [$this->getSluggedPlural(), $this->id]));
        }
        return null;
	}

	public function getRelativeUrl() {
		return preg_replace('/(http)(s)?\:\/\/[^\/]+/','',$this->getUrl());
	}

	public function getShortUrl() {
		return null;
	}

	public function getLink($anchor_text = null) {
		return "<a href='" . $this->getUrl() . "'>" . ($anchor_text ?: $this->name) . "</a>";
	}

}