<?php namespace Eae\Backoffice\Generic\Fields;

use Eae\Support\Contracts\ListableFieldInterface;
use Illuminate\Database\Eloquent\Builder;
use LaravelLocalization;
use View;

class DatePickerField extends BaseField implements ListableFieldInterface{
    protected $allowedInputTypes = array("datetime", "date", "time");
    protected $inputType = "datetime";
    
    public function __construct($config){
        
        parent::__construct($config);

        if(!empty($config["inputType"])){
            $this->setInputType($config["inputType"]);
        }    
    }
    
    public function getInputType(){
        return $this->inputType;    
    }
    
    public function setInputType($inputType = "datetime"){
        if(!in_array($inputType, $this->allowedInputTypes)){
            throw new InvalidConfigurationException("The field {$this->getName()} has an invalid inputType. Allowed values are datetime, date or time");    
        }
        
        $this->inputType = $inputType;    
    }

    protected function _getIcon(){
        switch($this->getInputType()){
            case "datetime":
            case "date":
                return "glyphicon-calendar";
            case "time":
                return "glyphicon-time";
            default:
                return "glyphicon-calendar";        
        }
    }
    
    public function buildSelect(Builder $query){
        if($this->isMultiLanguage()){
            $tablePrefix = $query->getModel()->languages()->getRelated()->getTable();        
        }else{
            $tablePrefix = $query->getModel()->getTable();    
        }
        
        $query->addSelect("{$tablePrefix}.{$this->name}");
        return $query;    
    }
    
    public function buildWhere(Builder $query, $searchPhrase){
        if(empty($searchPhrase) || !$this->isSearchable()){
            return $query;
        }
        
        if($this->isMultiLanguage()){
            $tablePrefix = $query->getModel()->languages()->getRelated()->getTable();        
        }else{
            $tablePrefix = $query->getModel()->getTable();    
        }
        
        $query->orWhere("{$tablePrefix}.{$this->name}", 'like', "%{$searchPhrase}%");
        return $query;
    }
    
    public function buildOrder(Builder $query, $sortOrder = "asc"){
        if($this->isMultiLanguage()){
            $tablePrefix = $query->getModel()->languages()->getRelated()->getTable();        
        }else{
            $tablePrefix = $query->getModel()->getTable();    
        }

        $query->orderBy("{$tablePrefix}.{$this->getName()}", $sortOrder); 
        return $query;
    }
    
    public function toArray(){
        $array = parent::toArray();
        $array["inputType"] = $this->inputType;
        return $array;  
    }
    
    public function toGridHeader(){
        return '<th data-column-id="' . $this->getName() . '">' . ucfirst($this->getLabel()) . '</th>';    
    }
    
    public function toForm($model, $enabled = true, $hidden = false){
        $html = "";
        $defaultLocale = LaravelLocalization::getDefaultLocale();
        if($this->isMultiLanguage()){
            $locales = LaravelLocalization::getSupportedLocales();

            foreach($locales as $locale => $localeData){
                $fieldName = $this->getName();
                $name = $fieldName . "[{$locale}]";
                $id = $fieldName . "_{$locale}";
                $errorKey = $fieldName . "." . $locale;
                $value = null;
                
                if($model->exists){
                    $languageModel = $model->languages->findByLocale($locale);
                    
                    if(!empty($languageModel)){
                        $value = $languageModel->$fieldName;
                    }
                }
                
                $html .= View::make(
                    "admin.generic.components.forms.datepicker", 
                    array(
                        "id"            => $id,
                        "errorKey"      => $errorKey,
                        "name"          => $name,
                        "label"         => $this->getLabel(),
                        "value"         => $value,
                        "inputType"     => $this->getInputType(),
                        "icon"          => $this->_getIcon(),
                        "language"      => $locale,
                        "defaultLang"   => $defaultLang,
                        "hide"          => ($hidden || $locale != $defaultLocale),
                        "enabled"       => $enabled,
                        "parentHidden"  => ($hidden && !empty($this->parent)),
                        "parent"        => $this->parent,
                        "info"          => $this->getInfo()    
                    ));    
            }    
        }else{
            $fieldName = $this->getName();
            $value = null;
            
            if($model->exists){
                $value = $model->$fieldName;    
            }
            $html .= View::make(
                    "admin.generic.components.forms.datepicker", 
                    array(
                        "id"            => $this->getName(),
                        "errorKey"      => $this->getName(),
                        "name"          => $this->getName(),
                        "label"         => $this->getLabel(),
                        "value"         => $value,
                        "inputType"     => $this->getInputType(),
                        "icon"          => $this->_getIcon(),
                        "hide"          => $hidden,
                        "enabled"       => $enabled,
                        "parentHidden"  => ($hidden && !empty($this->parent)),
                        "parent"        => $this->parent,
                        "info"          => $this->getInfo()    
                    ));      
        }
        
        return $html;
    }

    public function getValidationData($copyAllLang = false)
    {
        $validation = parent::getValidationData($copyAllLang);

        if(is_string($validation['values']) && empty($validation['values'])) {
            $validation['values'] = null;
        }
        elseif(is_array($validation['values'])) {
            foreach($validation['values'] as &$value) {
                if(empty($value)) {
                    $value = null;
                }
            }
        }
        return $validation;
    }
    
    public function getValidation(){
        $validation = parent::getValidation();

        
        switch($this->getInputType()){
            case "datetime":
                $rule = "date_format:Y-m-d H:i:s"; 
                break;
            case "date":
                $rule = "date_format:Y-m-d";
                break;
            case "time":
                $rule = "date_format:H:i";
                break;    
            
        }
        
        if(empty($validation)){
            return $rule;
        }else{
            return $validation . "|" . $rule;    
        }
        
    }
 
}
  

