<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use App\Http\Resources\Blocks as BlockResource;

class ProjectResource extends JsonResource
{
    protected $isDetail = FALSE;
    protected $linkStyle = [];

    public function __construct($resource, $isDetail = FALSE, array $linkStyle = [])
    {
        $this->resource = $resource;
        $this->isDetail = $isDetail;
        $this->linkStyle = $linkStyle;
    }

    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        $keywordArray = [];
        if (strlen(trim($this->project_keywords))) {
            $keywordArray = explode(':', $this->project_keywords);
        }

        $out = [
            'id' => (int)$this->id,
            'title' => $this->project_title,
            'keywords' => $keywordArray,
            'url' => '/' . $this->lang_slug,
            'languages' => new WebsiteObjectLanguages($this->getActiveWebsiteEntry()->languages),
            'url_label' => is_null($this->link_label) ? 'Launch Case' : $this->link_label,
            'image' => $this->_getImage($this->mainImage),
            'type' => $this->project_type
        ];

        if ($this->isDetail) {
            // SEO IMAGE
            $metaImage = $this->metaImage ? getImage($this->metaImage, '1200x630') : NULL;

            $out = array_merge($out, [
                'meta' => (object)[
                    'title' => $this->meta_title,
                    'description' => $this->meta_description,
                    'keywords' => $this->meta_keywords,
                    'image' => $metaImage
                ],
                'blocks' => BlockResource::collection($this->blocks),
            ]);
        }
        return $out;
    }

    private function _getImage($imageItem = NULL, $imageSize = '')
    {
        if ($imageItem) {
            return getImage($imageItem, $imageSize);
        } else {
            return (object)[
                'src' => null,
                'alt' => null,
            ];
        }
    }
}
