<?php

namespace Internetgalerie\IgDatapoolFe\Utility;

class NeedfulThings
{
    /**
     * Validation annotation that trigger the askerisk flag inidcating that it is required
     */
    public static $validatorsForRequiredFlag = ['NotEmpty', 'Internetgalerie.IgDatapoolFe:NotEmpty'];
    /**
     * Reflection service singleton
     *
     * @var TYPO3\CMS\\Extbase\Reflection\ReflectionService
     */
    public static $reflectionService = null;

    /**
     * Automagically add the reuired flag if property has an accroding validator
     *
     * @param  string property
     * @return bool
     */
    public static function isRequiredByAnnotation($property)
    {
        ;
        if (!($class = \Internetgalerie\IgDatapoolFe\Controller\ActionController::$currentObjectClass) || \Internetgalerie\IgDatapoolFe\ViewHelpers\FormViewHelper::$curForm -> isSearchForm()) {
            return false;
        }
        if (self::$reflectionService == null) {
            self::$reflectionService = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Reflection\\ReflectionService');
        }
        $methodTagsValues = self::$reflectionService -> getPropertyTagsValues($class, $property);
        return is_array($methodTagsValues['validate']) && count(array_intersect(self::$validatorsForRequiredFlag, \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $methodTagsValues['validate'][0]))) > 0;
    }

    /**
     * Automagically find date fields
     * this could be slow...
     *
     * @param string $class
     */
    public static function getDateFields($class)
    {
        if (self::$reflectionService == null) {
            self::$reflectionService = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Reflection\\ReflectionService');
        }

        $properties = self::$reflectionService -> getClassPropertyNames($class);
        $candidates = [];
        foreach ($properties as $p) {
            $tagStuff = self::$reflectionService -> getPropertyTagValues($class, $p, 'var');
            if ($tagStuff[0] == '\DateTime') {
                $candidates[] = $p;
            }
        }
        return $candidates;
    }

    /**
     * Resturns the field label providing a classname and e property
     *
     * @return string;
     */
    public static function getFieldLabelByProperty($property, $formObject=null, $tablename=null, $extensionName=null)
    {
        if (isset(\Internetgalerie\IgDatapoolFe\Controller\ActionController::$currentObjectClass)) {
            $class = \Internetgalerie\IgDatapoolFe\Controller\ActionController::$currentObjectClass;
            $table = self::classToTable($class);
        } elseif ($formObject!==null) {
            $class=get_class($formObject);
            $table = self::classToTable($class);
        } else {
            $table = $tablename;
        }

        //we can only resolve the first one in case of neste dobjects...
        $property = end(explode('.', $property));

        $field = self::propertyToField($property);
        $tableAndField = $table . '.' . $field;
        if ($extensionName!==null) {
            return  \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate($tableAndField, $extensionName);
        }
        return \Internetgalerie\IgDatapoolFe\Services\LangService::ll($tableAndField);
    }

    /**
     * get the object class
     */
    public static function classToTable($class)
    {
        $arr = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode('\\', $class, true);
        unset($arr[0]);
        return 'tx_' . strtolower(implode('_', $arr));
    }

    /**
     * get the object class
     */
    public static function propertyToField($camel)
    {
        return \TYPO3\CMS\Core\Utility\GeneralUtility::camelCaseToLowerCaseUnderscored($camel);
    }

    /**
     * Get the file extension
     *
     * @param $file string filename
     */
    public static function getFileExt($file)
    {
        return strtolower(substr(strrchr(basename($file), '.'), 1));
    }

    /**
     * get the current FE language
     */
    public static function getCurLang($default = 'de')
    {
        if (!$GLOBALS['TSFE'] -> sys_language_uid) {
            return $default;
        } else {
            return $GLOBALS['TSFE'] -> lang;
        }
    }

    /**
     * we override $myArgs with the request args that start with @, but only if they are not set in myargs
     *
     * @param  array                          $myArgs
     * @param  \TYPO3\CMS\Extbase\Mvc\Request $request
     * @return array
     */
    public static function keepAndOverrideArgs($myArgs, \TYPO3\CMS\Extbase\Mvc\Request $request, array $prefixes = [])
    {
        if (!is_array($myArgs)) {
            $myArgs = [];
        }
        $args = $request -> getArguments();
        foreach ($args as $key => $val) {
            if (substr($key, 0, 1) != '@') {
                continue;
            }
            //we want to change something
            if (isset($myArgs[$key])) {
                // both are arrays, override
                if (is_array($val) && is_array($myArgs[$key])) {
                    //both arrays: set old values, then override them with new ones.
                    $temp = $val;
                    \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($temp, $myArgs[$key]);
                    $myArgs[$key] = $temp;
                }
            } else {
                $myArgs[$key] = $val;
            }
        }
        if (!empty($prefixes)) {
            foreach ($prefixes as $key) {
                if (substr($key, 0, 1)=='@') {
                    continue;
                }
                if (!isset($myArgs[$key]) && $request->hasArgument($key)) {
                    $myArgs[$key] = $request->getArgument($key);
                }
            }
        }
        return $myArgs;
    }
}
