<?php
namespace ProVM\Money;

use Carbon\CarbonInterval;
use ProVM\Common\Alias\Model;
use ProVM\Common\Factory\Model as ModelFactory;

/**
 * @property int $id
 * @property Currency $currency_id
 * @property string $url
 * @property \DateInterval $frecuency
 */
class Source extends Model {
  public static $_table = 'sources';

  protected $currency;
  public function currency(): ?Currency {
    if ($this->currency === null) {
      $this->currency = $this->childOf(Currency::class, [Model::SELF_KEY => 'currency_id']);
    }
    return $this->currency;
  }
  public function frecuency(\DateInterval $frecuency = null) {
    if ($frecuency == null) {
      return CarbonInterval::createFromDateString($this->frecuency);
    }
    $this->frecuency = CarbonInterval::getDateIntervalSpec($frecuency);
  }

  protected static $fields = ['currency_id', 'url', 'frecuency'];
  public static function add(ModelFactory $factory, $info) {
    $input = array_intersect_key((array) $info, array_combine(self::$fields, self::$fields));
    $input['frecuency'] = CarbonInterval::createFromDateString($input['frecuency']);
    $source = $factory->find(Source::class)->where([['currency_id', $input['currency_id']], ['url', $input['url']]])->one();
    $created = false;
    $result = (object) compact('input', 'source', 'created');
    if (!$source) {
      $source = $factory->create(Source::class, $input);
      $created = $source->save();
      $result->created = $created;
    }
    $result->source = $source->asArray();
    return $result;
  }
  public function edit($info): bool {
    $data = array_intersect_key((array) $info, array_combine(self::$fields, self::$fields));
    $edited = false;
    foreach ($data as $field => $value) {
      if ($this->{$field} != $value) {
        $this->{$field} = $value;
        $edited = true;
      }
    }
    if ($edited) {
      $edited = $this->save();
    }
    return $edited;
  }
  public function asArray(): array {
    $output = parent::asArray();
    $output['currency'] = $this->currency()->asArray();
    $output['frecuency'] = $this->frecuency()->spec();
    return $output;
  }
}
