<?php

namespace App\Libs\Backoffice\Generic;

use App\Libs\Facades\Localization;
use DirectoryIterator;

class ContentTypes
{

    protected $collection;

    public function __construct()
    {
        $dir = new DirectoryIterator(config_path('backoffice/generic'));

        $types = array();
        foreach ($dir as $fileinfo) {
            if (!$fileinfo->isDot()) {
                $type = preg_replace('/\\.[^.\\s]{3,4}$/', '', $fileinfo->getFilename());
                $types[] = new ContentType($type);
            }
        }

        $this->collection = new ContentTypeCollection($types);
    }

    public function getScripts()
    {
        $scripts = array(
            'genericModalForm' => path_asset('path.backoffice.js_path').'/view/backend-generic-form-modal.js',
            'genericStackableModals' => path_asset('path.backoffice.js_path').'/view/backend-generic-stackable-modals.js',
            'genericForm' => path_asset('path.backoffice.js_path').'/view/backend-generic-form.js',
            'langPicker' => path_asset('path.backoffice.js_path').'/view/backend-lang-tab-picker.js',
        );
        $dir = new DirectoryIterator(app_path('Libs/Backoffice/Generic/Fields'));
        foreach ($dir as $fileinfo) {
            if (!$fileinfo->isDot()) {
                $fieldType = preg_replace('/\\.[^.\\s]{3,4}$/', '', $fileinfo->getFilename());
                $class = "App\\Libs\\Backoffice\\Generic\\Fields\\{$fieldType}";
                $script = $class::getScript();
                if (!is_null($script)) {
                    $scripts = array_merge($scripts, $script);
                }
            }
        }

        return $scripts;
    }

    public function allPageable()
    {
        $website = Localization::getWebsite();
        $templates = config('backoffice.generic.page.templates')[$website->id];

        $pageContentTypes = ['page'];
        // Gets page content types
        foreach ($templates as $template) {
            if (!empty($template['detailContentType'])) {
                $pageContentTypes[] = $template['detailContentType'];
            }
        }

        return $this->collection->filter(function ($contentType) use ($pageContentTypes) {
            return in_array($contentType->getType(), $pageContentTypes);
        });
    }

    public function __call($method, $parameters)
    {
        return call_user_func_array(array($this->collection, $method), $parameters);
    }


}
