<?php namespace Eae\Backoffice;

use Input;
use Formatter;
use Eae\Support\Formatter as BasicFormatter;

/**
* Transforms generic fields through preValidation
*/

class GenericFormatter
{
    private $formater;
    
    public function __construct(BasicFormatter $formater = null)
    {
        if(is_null($formater)){
            $this->formater = Formatter::instance();    
        }else{
            $this->formater = $formater;    
        }
        
    }
    
    /**
     * Transforms the Input based on the generic backoffice preValidation value
     * $fields [array] -> fields array from the generic backoffice config
     * returns nothing
     */ 
    public function transformFields($fields){
        if(!is_array($fields)){
            throw new InvalidArgumentException("The values and fields arguments must be arrays");    
        } 
        
        $languages = getAvailableLanguages();

        foreach($fields as $field){
            if(empty($field["preValidation"])){
                continue;
            }

            if(!empty($field["multiLanguage"])){
                foreach($languages as $languageIso => $langProps){
                    $fieldName = $field['name'] . "_" . $languageIso;
                    $this->_prepareRequestItem($fieldName, $field["preValidation"]);   
                }    
            }else{
                $this->_prepareRequestItem($field['name'], $field["preValidation"]);     
            }
        }          
    }
    
    private function _prepareRequestItem($fieldName, $rules){
        if(Input::has($fieldName)){
            $inputValue = Input::get($fieldName);
            if(is_string($inputValue)){
                $inputValue = $this->transformItem($inputValue, $rules);
                Input::merge(array($fieldName => $inputValue));
            }
        }        
    }
    
    public function __call($name, $parameters){
        return call_user_func_array(array($this->formater, $name), $parameters);
    }
}
