<?php
namespace Hilco\Models;

use DB;
use NumberFormatter;
use DateTime;

class DatafeedField_Datafeed extends WebModel {
    protected $table = 'DatafeedField_Datafeed';

    protected $fillable = ['datafeed_id', 'datafeedfield_id', 'sequence_number', 'enabled', 'overrideName', 'overrideOrder', 'deleted_at'];

    public function datafeed()
    {
        return $this->belongsTo(Datafeed::class);
    }

    public function datafeedfield()
    {
        return $this->belongsTo(DatafeedField::class, 'datafeedfield_id', 'id');
    }

    public function transformations() {
        return $this->hasMany(DatafeedFieldTransformation::class, 'datafeedfield_datafeed_id', 'id');
    }

    public function bindingvalues() {
        return $this->hasMany(DatafeedFieldBindingValue::class, 'datafeedfield_datafeed_id', 'id');
    }

    public function saveBindingValue($binding_type, $value) {
        $bindingRule = $this->datafeedfield->getBindingRule($binding_type);

        $bindingValue = $this->getBindingValue($bindingRule);
        if ($bindingValue == null) {
            $bindingValue = new DatafeedFieldBindingValue();
            $bindingValue->datafeedfield_datafeed_id = $this->id;
            $bindingValue->datafeedfieldbindingrule_id = $bindingRule->id;
        }
        
        $bindingValue->value = $value;
        $bindingValue->save();

        return $bindingValue;
    }
    
    public function getBindingValue($bindingRule) {

        return DatafeedFieldBindingValue::forBindingRule($bindingRule->id)->forDatafeedFieldAttachment($this->id)->first();
    }

    public function getBindingValueValue($bindingRule) {

        if ($bindingRule == null) {
            return null;
        }
        $bindingValue = DatafeedFieldBindingValue::forBindingRule($bindingRule->id)->forDatafeedFieldAttachment($this->id)->first();

        return $bindingValue != null ? $bindingValue->value : null;
    }

    public function scopeForDatafeed($query, $datafeed_id)
    {
        return $query->where('datafeed_id', '=', $datafeed_id);
    }
    
    public function scopeForDatafeedfield($query, $datafeedField_id)
    {
        return $query->where('datafeedfield_id', '=', $datafeedField_id);
    }

    public function scopeNotForSequenceNumber($query, $sequence_number)
    {
        return $query->where('sequence_number', '!=', $sequence_number);
    }
    
    public function scopeForSequenceNumber($query, $sequence_number)
    {
        return $query->where('sequence_number', '=', $sequence_number);
    }
    
    public function getDefaultNameAttribute(){
        return $this->datafeedfield->defaultName;
    }
    
    public function getFieldNameAttribute(){
        if (is_null($this->overrideName) || $this->overrideName === ''){
            $bindingRule = $this->datafeedfield->getBindingRule('language');
            if ($bindingRule != null) {
                $languageValue = $this->getBindingValueValue($bindingRule);
                return $this->datafeedfield->getTranslationWithDefaultForReal('defaultName', $languageValue);
            }

            return $this->defaultName;
        }else{
            return $this->overrideName;
        }
    }

    public function getCalculatedOrderAttribute(){
        return isset($this->overrideOrder)? $this->overrideOrder : $this->datafeedfield->defaultOrder;
    }

    public function getCalculatedOrderIndexAttribute(){
        return $this->calculatedOrder - 1;
    }

    public function getFieldNameWithIdAttribute() {
        return $this->fieldName."__".$this->id;
    }
    
    public function getSelectValueAttribute(){
        if (!is_null($this->datafeedfield->rawValue) && $this->datafeedfield->rawValue !== '') {
            $sql = $this->datafeedfield->rawValue;
            $bindings = [];
            foreach($this->datafeedfield->bindingrules as $bindingRule) {
                foreach($this->bindingvalues as $bindingValue) {
                    if ($bindingRule->bindingType === $bindingValue->datafeedfieldbindingrule->bindingType) {
                        $pos = strpos($sql, "?");
                        if ($pos !== false) {
                            $sql = substr_replace($sql, "'$bindingValue->value'", $pos, strlen("?"));
                        }
                    }
                }
            }
            return DB::raw($sql ." as `$this->fieldName"."__"."$this->id`", $bindings);
        }else{
            return DB::raw("`".$this->datafeedfield->tableName."`.`".$this->datafeedfield->columnName."` as `$this->fieldName"."__"."$this->id`");
        }
    }


    public function currencyFormat($value, $currency) {
        if ($this->currency_formatter != null && $this->currency_formatter !== "0") {
            $currencyFormatter = new NumberFormatter($this->currency_formatter, NumberFormatter::CURRENCY);
            return $currencyFormatter->formatCurrency($value, $currency);
        }
        return $value;
    }

    public function dateFormat($value) {
        if ($this->date_formatter != null && $this->date_formatter !== "0") {
            $fromFormat = $this->datafeedfield->sourceDateFormat;
            $toFormat = $this->date_formatter;

            $datetime = DateTime::createFromFormat($fromFormat, $value);
            return $datetime->format($toFormat);
        } else {
            return $value;
        }

    }
}
