<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

use Shopware\Plugins\ViisonCommon\Controllers\ViisonCommonBaseController;

class Shopware_Controllers_Backend_ViisonCommonGridLabelPrinting extends ViisonCommonBaseController
{
    /**
     * @var array|null
     */
    protected $gridLabelTemplates = null;

    /**
     * Responds a list with the names, titles, dimensions etc. of all available grid label templates.
     */
    public function getGridLabelTemplateListAction()
    {
        $this->View()->assign([
            'success' => true,
            'data' => $this->getGridLabelTemplates(),
            'total' => count($this->getGridLabelTemplates()),
        ]);
    }

    /**
     * @return array
     */
    protected function getGridLabelTemplates()
    {
        return ($this->gridLabelTemplates) ?: [];
    }

    /**
     * Parses the cols and rows from the names of the given $rawTemplates and usese them to create an associative array
     * for each of them.
     *
     * @param array $rawTemplates
     * @param string|null $defaultTemplateName
     */
    protected function setRawGridLabelTemplates(array $rawTemplates, $defaultTemplateName = null)
    {
        $this->gridLabelTemplates = array_map(
            function (array $template) use ($defaultTemplateName) {
                list($name, $title) = $template;
                $dimensions = [];
                preg_match('/^(\\d+)x(\\d+)/', $name, $dimensions);

                return [
                    'name' => $name,
                    'title' => $title,
                    'default' => $name === $defaultTemplateName,
                    'numCols' => intval($dimensions[1]),
                    'numRows' => intval($dimensions[2]),
                ];
            },
            $rawTemplates
        );
    }

    /**
     * Checks if a template with the given name exists.
     *
     * @param string $layoutName
     * @return boolean
     */
    protected function isValidGridLabelTemplate($layoutName)
    {
        foreach ($this->getGridLabelTemplates() as $template) {
            if ($template['name'] === $layoutName) {
                return true;
            }
        }

        return false;
    }
}
