<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use App\Http\Resources\WebLinks as WebLinkResource;
use App\Http\Resources\WebLinksCollection;
use App\Http\Resources\SimpleLinksCollection;
use App\Http\Resources\SimpleLinks as SimpleLinksResource;
use App\Http\Resources\TextLoops as TextLoopResource;
use App\Http\Resources\Quotes as QuoteResource;
use App\Http\Resources\Categories as CategoryResource;
use App\Http\Resources\Tags as TagResource;
use App\Http\Resources\AddonsLists as AddonsListResource;
use App\Http\Resources\HighlightsCommunity as HighlightsCommunityResource;
use App\Http\Resources\HighlightsCommunityCollection;
use App\Http\Resources\HighlightsProduct as HighlightsProductResource;
use App\Http\Resources\HighlightsProductCollection;
use App\Http\Resources\HighlightsEvent as HighlightsEventResource;
use App\Http\Resources\HighlightsKit as HighlightsKitResource;
use App\Http\Resources\TabsContainer as TabsContainerResource;
use App\Http\Resources\TabsContainerCollection as TabsContainerCollectionResource;
use App\Http\Resources\ListBoxes as ListBoxResource;
use App\Http\Resources\Voucher as VoucherResource;
use App\Http\Resources\BlockLists as BlockListsResource;
use App\Http\Resources\PageTabsCollection as PageTabsResource;
use App\Http\Resources\AccordionItemCollection;
use App\Http\Resources\HighlightsAddons;
use App\Http\Resources\HighlightsAddonsCollection;
use App\Models\GenericBackoffice\WebsiteObject;

use App\Models\Theme;
use App\Models\ThemeLanguage;
use App\Models\Publication;
use App\Models\PublicationLanguage;
use App\Models\ProductGroup;
use App\Models\ProductGroupLanguage;
use App\Models\Category;
use App\Models\CategoryLanguage;
use App\Models\Component;
use App\Models\ComponentLanguage;
use App\Models\Platform;
use App\Models\PlatformLanguage;
use App\Models\Country;
use App\Models\CountryLanguage;
use App\Models\ContactAddress;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;

use Illuminate\Support\Str;

class Blocks extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function __construct($resource)
    {
        $this->resource = $resource;
    }

    public function toArray($request)
    {
        // Default data that we need to return on every block
        $out = [
            'id'          => (int)$this->id,
            'title'       => $this->block_title ? $this->block_title : $this->title,
            'type'        => Str::camel($this->type),
        ];

        // Specific block data per type
        $out = array_merge($out, $this->_getBlockData());

        return $out;
    }

    private function parseFilters($title, $requestName, $requestField, $arrayData)
    {
        if (gettype($arrayData) !== 'array') {
            $thisType = gettype($arrayData);
            throw new \ErrorException('parseFilters expects an array instead of ' . ucwords($thisType));
        }
        $tempObj = (object)[];
        $tempObj->title = $title;
        $tempObj->requestName = $requestName;
        $tempObj->requestField = $requestField;
        $tempObj->list = $arrayData;
        return [$tempObj];
    }

    // Header Parser
    private function _getBlockData()
    {
        $out = [];
        switch ($this->type) {
            case 'blockHero':
                $out = $this->_getBlockHero();
                break;
            case 'blockHeroHighlight':
                $out = $this->_getBlockHeroHighlight();
                break;
            case 'blockHighlightExternal':
                $out = $this->_getBlockHighlightExternal();
                break;
            case 'blockSliderQuote':
                $out = $this->_getBlockSliderQuote();
                break;
            case 'blockNewsletter':
                $out = $this->_getBlockNewsletter();
                break;
            case 'blockHighlightsCommunity':
                $out = $this->_getBlockHighlightsCommunity();
                break;
            case 'blockImageText':
                $out = $this->_getBlockImageText();
                break;
            case 'blockCenteredImageText':
                $out = $this->_getBlockCenteredImageText();
                break;
            case 'blockHighlightsProduct':
                $out = $this->_getBlockHighlightsProduct();
                break;
            case 'blockHighlightsCard':
                $out = $this->_getBlockHighlightsCard();
                break;
            case 'blockVersionsList':
                $out = $this->_getBlockVersionsList();
                break;
            case 'blockPublicationsList':
                $out = $this->_getBlockPublicationsList();
                break;
            case 'blockCommunityList':
                $out = $this->_getBlockCommunityList();
                break;
            case 'blockListBox':
                $out = $this->_getBlockListBox();
                break;
            case 'blockDisclaimer':
                $out = $this->_getBlockDisclaimer();
                break;
            case 'blockPageTabs':
                $out = $this->_getBlockPageTabs();
                break;
            case 'blockProductsList':
                $out = $this->_getBlockProductsList();
                break;

            case 'blockSchematicsList':
            case 'blockFirmwaresList':
            case 'blockThreeDModelsList':
                $out = $this->_getModelFiltersList();
                break;
            case 'blockApisList':
                $out = $this->_getBlockApisList();
                break;
            case 'blockResellersList':
                $out = $this->_getCountryFiltersList();
                break;

            case 'blockHighlightsEvent':
                $out = $this->_getBlockHighlightsEvent();
                break;
            case 'blockFaq':
                $out = $this->_getBlockFaq();
                break;
            case 'blockContactForm':
                $out = $this->_getBlockContactForm();
                break;
            case 'blockEventsList':
                $out = $this->_getBlockEventsList();
                break;
            case 'blockTitleSubtitleText':
                $out = $this->_getBlockTitleSubtitleText();
                break;
            case 'blockHighlightsAddons':
                $out = $this->_getBlockHighlightsAddons();
                break;
            case 'blockHighlightsTutorial':
                $out = $this->_getBlockHighlightsTutorial();
                break;
            case 'blockTutorialsList':
                $out = $this->_getBlockTutorialsList();
                break;
        }
        return $out;
    }

    // Block Hero
    private function _getBlockHero()
    {
        if ($this->blockImage) {
            $image = getImage($this->blockImage, '1920x845');
        } else {
            $image = (object)[];
            $image->url = null;
            $image->alt = null;
        }
        $stampSvg = getDocument($this->stampSvg);
        $out = [
            'title'         => $this->block_title,
            'smallTitle'    => $this->small_title,
            'subTitle'      => $this->sub_title,
            'sideTitle' => $this->side_info_title,
            'sideLinks'      => WebLinkResource::collection($this->blockHeroSideWebLinks),
            'hasStamp'      => $this->has_stamp == 3 ? true : false,
            'stampSvg'      => $stampSvg ? $stampSvg->url : '',
            'stampLink'     => $this->stamp_link,
            'image'         => $image,
            'links'      => new WebLinksCollection($this->blockHeroWebLinks),
            'textLoop'      => TextLoopResource::collection($this->textLoop),
            'darkMode'      => $this->dark_mode,
        ];

        return $out;
    }

    // Block Hero Highlight
    private function _getBlockHeroHighlight()
    {
        if ($this->blockImage) {
            $image = getImage($this->blockImage, '1366x768');
        } else {
            $image = (object)[];
            $image->url = null;
            $image->alt = null;
        }
        $link = $this->block_data;
        if ($link) {
            if (array_key_exists('objectId', $link)) {
                $websiteObject = WebsiteObject::find($link['objectId']);
                if ($websiteObject) {
                    $link['url'] = $websiteObject->uri;
                }
            }
        }
        unset($link['objectId']);
        $out = [
            'id'        => (int)$this->id,
            'title'     => $this->block_title,
            'smallTitle'     => $this->small_title,
            'subTitle'     => $this->sub_title,
            'image'         => $image,
            'link'         => $link,
            'darkMode'    => (bool)$this->dark_mode,
        ];

        return $out;
    }

    // Block Highlight External
    private function _getBlockHighlightExternal()
    {
        $data = $this->block_data;
        if ($data) {
            if (array_key_exists('objectId', $data)) {
                $websiteObject = WebsiteObject::find($data['objectId']);
                if ($websiteObject) {
                    $data['url'] = $websiteObject->uri;
                }
            }
        }
        unset($data['objectid']);

        $out = [
            'id'        => (int)$this->id,
            'title'     => $this->block_title,
            'link'     => $data,
        ];

        return $out;
    }

    // Block Slider Quote
    private function _getBlockSliderQuote()
    {
        $out = [
            'quotes'    => QuoteResource::collection($this->blockSliderQuote),
        ];

        return $out;
    }

    // Block Newsletter
    private function _getBlockNewsletter()
    {
        $out = [
            'id'        => (int)$this->id,
            'title'         => $this->block_title,
            'subTitle'   => $this->sub_title,
        ];

        return $out;
    }

    // Block Highlights Community
    private function _getBlockHighlightsCommunity()
    {
        $out = [
            'highlights'    => new HighlightsCommunityCollection($this->blockProjects),
        ];

        return $out;
    }

    private function _getBlockHighlightsEvent()
    {
        $out = [
            'highlights'    => HighlightsEventResource::collection($this->blockEvents),
        ];

        return $out;
    }

    // Block Image Text
    private function _getBlockImageText()
    {
        if ($this->blockImage) {
            $image = getImage($this->blockImage, '1366x1366');
        } else {
            $image = new Collection();
            $image->url = null;
            $image->alt = null;
        }
        $out = [
            'title'      => $this->block_title,
            'subTitle'   => $this->sub_title,
            'smallTitle' => $this->small_title,
            'image'      => $image,
            'alignment'  => $this->alignment,
            'variation'  => $this->variation,
            'textSize'   => $this->text_size,
        ];
        return $out;
    }

    // Block Centered Image Text
    private function _getBlockCenteredImageText()
    {
        if ($this->blockImage) {
            $image = getImage($this->blockImage, '790x590');
        } else {
            $image = (object)[];
            $image->url = null;
            $image->alt = null;
        };
        $link = $this->block_data;
        if ($link) {
            if (array_key_exists('objectId', $link)) {
                $websiteObject = WebsiteObject::find($link['objectId']);
                if ($websiteObject) {
                    $link['url'] = $websiteObject->uri;
                }
            }
        }
        unset($link['objectId']);
        $out = [
            'title'      => $this->block_title,
            'subTitle'   => $this->sub_title,
            'smallTitle' => $this->small_title,
            'image'      => $image,
            'link'       => $link,
        ];

        return $out;
    }

    // Block Highlights Product
    private function _getBlockHighlightsProduct()
    {
        $out = [
            'highlights'    => new HighlightsProductCollection($this->blockProducts),
        ];

        return $out;
    }

    // Block Highlights Card
    private function _getBlockHighlightsCard()
    {
        $out = [
            'highlights'    => new HighlightsCardCollection($this->blockGeneralCards),
        ];

        return $out;
    }

    // Block Versions List
    private function _getBlockVersionsList()
    {
        $out = [
            'tabs'  => TabsContainerResource::collection($this->blockTabsContainer),
        ];

        return $out;
    }

    // Block Products List
    private function _getBlockProductsList()
    {
        $models = ProductGroup::full()->select('id', 'title')->get()->map(function ($item, $index) {
            return [
                "id" => $item["id"],
                "title" => $item["title"]
            ];
        })->toArray();
        $parsedModels = $this->parseFilters('All Models', 'model', 'id', $models);

        $components = Component::full()->select('id', 'title')->get()->map(function ($item, $index) {
            return [
                "id" => $item["id"],
                "title" => $item["title"],
            ];
        })->toArray();
        $parsedComponents = $this->parseFilters('All Components', 'component', 'id', $components);
        $out = [
            'title'   => $this->block_title,
            'filters' => array_merge($parsedComponents, $parsedModels),
            'tags'    => TagResource::collection($this->blockTags),
        ];

        return $out;
    }

    // Block Publications List
    private function _getBlockPublicationsList()
    {
        $years = Publication::full()->select('publication_date')->distinct()->orderBy('publication_date', 'DESC')->get()->pluck('publication_date');
        $filteredYears = [];
        foreach ($years as $year) {
            $filteredYears[] = $year->format('Y');
        }
        $filteredYears = array_unique($filteredYears);
        $arrYears = [];
        foreach ($filteredYears as $year) {
            $obj2Years = [
                'title' => $year,
            ];
            $arrYears[] = $obj2Years;
        }
        $parsedYears = $this->parseFilters('All Years', 'year', 'title', $arrYears);

        $themes = Theme::full()->select('id', 'block_title')->get()->map(function ($item, $index) {
            return [
                "id" => $item["id"],
                "title" => $item["block_title"]
            ];
        })->toArray();
        $parsedThemes = $this->parseFilters('All Themes', 'theme', 'id', $themes);

        // Uncomment the Line below when they want Themes again
        //$filters = array_merge($parsedYears, $parsedThemes);
        $filters = array_merge($parsedYears, []);
        $out = [
            'title'         => $this->block_title,
            'filters'       => $filters,
        ];

        return $out;
    }

    // Block Community List
    private function _getBlockCommunityList()
    {
        $categories = Category::full()->select('id', 'title')->get()->map(function ($item, $index) {
            return [
                "id" => $item["id"],
                "title" => $item["title"],
            ];
        })->toArray();
        $parsedCategories = $this->parseFilters('All Categories', 'categories', 'id', $categories);
        $out = [
            'title'         => $this->block_title,
            'smallTitle'    => $this->small_title,
            'subTitle'    => $this->sub_title,
            'filters'    => array_merge([], $parsedCategories),
            'tags'          => TagResource::collection($this->blockTags),
        ];

        return $out;
    }

    // Block List Box
    private function _getBlockListBox()
    {
        $out = [
            'items'         => ListBoxResource::collection($this->blockListBoxItems),
        ];

        return $out;
    }

    // Block Disclaimer
    private function _getBlockDisclaimer()
    {
        $out = [
            'text'         => $this->text,
        ];

        return $out;
    }

    //Block Page Tabs
    private function _getBlockPageTabs()
    {
        $out = [
            'pageTabs'  => new PageTabsResource($this->blockPageTabs)
        ];

        return $out;
    }

    //Block to get Model Filters
    private function _getModelFiltersList()
    {
        $models = ProductGroup::full()->select('id', 'title')->get()->map(function ($item, $index) {
            return [
                "id" => $item["id"],
                "title" => $item["title"]
            ];
        })->toArray();
        $parsedModels = $this->parseFilters('All Models', 'model', 'id', $models);
        $filters = array_merge([], $parsedModels);
        $out = [
            'title'         => $this->block_title,
            'filters'       => $filters,
        ];
        return $out;
    }


    //Block to get Platform Filters
    private function _getPlatformFiltersList()
    {
        $platforms = Platform::full()->select('id', 'title')->get()->map(function ($item, $index) {
            return [
                "id" => $item["id"],
                "title" => $item["title"]
            ];
        })->toArray();
        $parsedPlatforms = $this->parseFilters('All Compatibilities', 'platform', 'id', $platforms);
        $filters = array_merge([], $parsedPlatforms);
        $out = [
            'title'         => $this->block_title,
            'filters'       => $filters,
        ];
        return $out;
    }

    //Block to get Api's Filters
    private function _getBlockApisList()
    {
        $platforms = Platform::full()->select('id', 'title')->get()->map(function ($item, $index) {
            return [
                "id" => $item["id"],
                "title" => $item["title"]
            ];
        })->toArray();
        $parsedPlatforms = $this->parseFilters('All Compatibilities', 'platform', 'id', $platforms);
        $models = ProductGroup::full()->select('id', 'title')->get()->map(function ($item, $index) {
            return [
                "id" => $item["id"],
                "title" => $item["title"]
            ];
        })->toArray();
        $parsedModels = $this->parseFilters('All Models', 'model', 'id', $models);
        $filters = array_merge($parsedModels, $parsedPlatforms);
        $out = [
            'title'         => $this->block_title,
            'filters'       => $filters,
        ];
        return $out;
    }

    //Block to get Country Filters
    private function _getCountryFiltersList()
    {
        $countries = Country::full()->select('id', 'country_name')->get()->map(function ($item, $index) {
            return [
                "id" => $item["id"],
                "title" => $item["country_name"]
            ];
        })->toArray();
        $parsedCountries = $this->parseFilters('All Countries', 'country', 'id', $countries);
        $out = [
            'title'         => $this->block_title,
            'filters'       => $parsedCountries,
        ];
        return $out;
    }

    //Block Accordion
    private function _getBlockFaq()
    {
        $out = [
            'printTitle' => $this->block_faq_count > 1,
            'accordions' => new AccordionItemCollection($this->blockFaq),
            'childrenAccordion' => false,
        ];

        return $out;
    }

    //Block Contact Form
    private function _getBlockContactForm()
    {
        $contact = ContactAddress::full()->select('*')->where('is_main_address', 1)->first();
        $out = [
            'subTitle' => $this->sub_title,
            'contact'  => null
        ];
        if ($contact) {
            $out['contact'] = [
                'title' => $contact->frontend_title,
                'address' => $contact->address,
                'zipcode' => $contact->zipcode,
                'city' => $contact->city,
                'country' => $contact->country,
                'fullNumber' => $contact->full_number,
                'contactEmail' => $contact->contact_email,
                'salesEmail' => $contact->sales_email,
                'supportEmail' => $contact->support_email,
            ];
        }
        return $out;
    }

    //Block Events List
    private function _getBlockEventsList()
    {
        $out = [
            'title'      => $this->block_title,
            'smallTitle' => $this->small_title,
            'subTitle'   => $this->sub_title,
        ];
        return $out;
    }

    //Block Title Subtext
    private function _getBlockTitleSubtitleText()
    {
        $out = [
            'title'    => $this->block_title,
            'subTitle' => $this->sub_title,
            'text'     => $this->text,
        ];
        return $out;
    }

    //Block Highlights Addons
    private function _getBlockHighlightsAddons()
    {
        $out = [
            'title' => $this->block_title,
            'highlights' => new HighlightsAddonsCollection($this->blockAddons),
        ];
        return $out;
    }

    // Block Highlights Tutorial
    private function _getBlockHighlightsTutorial()
    {
        $out = [
            'highlights'    => new HighlightsTutorialCollection($this->blockTutorialCards),
        ];

        return $out;
    }

    // Block Normal Tabs
    private function _getBlockTutorialsList()
    {
        $models = ProductGroup::full()->select('id', 'title')->get()->map(function ($item, $index) {
            return [
                "id" => $item["id"],
                "title" => $item["title"]
            ];
        })->toArray();
        $parsedModels = $this->parseFilters('All Models', 'model', 'id', $models);

        $out = [
            'tabs'    => new NormalTabsCollection($this->blockTutorialsList),
            'filters' => $parsedModels,
        ];

        return $out;
    }
}
