<?php namespace Eae\Transformation\Transformer;

use League\Fractal;
use Lang;
use Occurrence;
use Location;

class MapTransformer extends Fractal\TransformerAbstract
{

    protected $defaultIncludes = [
        'location'
    ];

    protected $availableIncludes = [];
    protected $withFilters = [];

    public function __construct($withFilters = FALSE)
    {
        $this->withFilters = $withFilters;
    }

    public function transform(Occurrence $occurrence)
    {
        $image = $occurrence->occurrenceImage;
        $occurrenceDate = db_date_to_carbon($occurrence->occurrence_date);
        $isStory = FALSE;
        $slug = $occurrence->lang_slug;
        if ($occurrence->is_story === 'yes') {
            $isStory = TRUE;
            $slug = $occurrence->story->lang_slug;
        }

        $out = [
            'id'           => (int)$occurrence->id,
            'title'        => $occurrence->title ? $occurrence->title : '',
            'description'  => $occurrence->occurrence_description ? $occurrence->occurrence_description : '',
            'audio'        => $occurrence->occurrence_audio ? $occurrence->occurrence_audio : '',
            'image'        => isset($image->filename) ? getMediaUrl($image->filename, '260x388') : '',
            'thumb_image'  => isset($image->filename) ? getMediaUrl($image->filename, '150x96') : '',
            'mobile_image' => isset($image->filename) ? getMediaUrl($image->filename, '400x195') : '',
            'slug'         => $slug,
            'date'         => $occurrenceDate->format("d-m-Y"),
            'is_story'     => $isStory
        ];

        if ($this->withFilters) {
            $out['filters'] = $this->_filters($occurrence);
        }


        return $out;
    }

    protected function _filters(Occurrence $occurrence)
    {
        $out['personalities'] = $occurrence->personalities->lists("id");
        $out['themes'] = $occurrence->themes->lists("id");
        $out['categories'] = $occurrence->categories->lists("id");
        $out['cities'] = $occurrence->locations->lists("id");

        if (!$occurrence->locations->isEmpty()) {
            $out['countries'] = $occurrence->locations
                ->filter(function (Location $location) {
                    return !is_null($location->country_id);
                })->lists("country_id");
        } else {
            $out['countries'] = [];
        }

        return $out;
    }

    public function includeLocation(Occurrence $occurrence)
    {
        if ($occurrence->locations->isEmpty()) {
            return NULL;
        }

        return $this->item($occurrence->locations->first(), new LocationTransformer());
    }
}
