<?php
namespace Dipper\Foundation\Repository;

use stdClass;
use Illuminate\Support\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;

/**
 * Interface TransformableRepository.
 */
trait TransformableRepository
{
    /**
     * @var bool
     */
    protected $needTransform = false;

    protected $loads = [];

    /**
     * 数据处理中间件.
     *
     * @param mixed $result
     *
     * @return mixed
     */
    public function parserResult($result)
    {
        if ($this->needTransform) {
            if (!empty($this->loads) && !(($result instanceof Collection && !$result instanceof EloquentCollection))) {
                foreach ($this->loads as $load) {
                    $result->load($load);
                }
            }

            if ($result instanceof LengthAwarePaginator || $result instanceof Paginator || $result instanceof Collection) {
                $result = $result->map(function ($model) {
                    if (!$model instanceof stdClass) {
                        return $this->transform($model);
                    }

                    return $model;
                });
            } elseif ($result instanceof Model) {
                $result = $this->transform($result);
            }
        }

        return $result;
    }

    /**
     * 开启格式数据格式转化
     *
     * @return $this
     */
    public function withTransform()
    {
        $this->needTransform = true;
        
        return $this;
    }

    /**
     * 关闭格式数据格式转化
     *
     * @return $this
     */
    public function skipTransform()
    {
        $this->needTransform = false;
        
        return $this;
    }


    /**
     * 数据格式化
     * 用法：继承该方法，处理数据并返回结果。
     *
     * @param mixed $result
     *
     * @return mixed
     */
    public function transform($model)
    {
        return $model->toArray();
    }

    /**
     * save a record in the database.
     *
     * @return int
     */
    public function save()
    {
        if (!empty($this->loads)) {
            foreach ($this->loads as $load) {
                list($column, $foo) = explode(':', $load);
                unset($this->model[$column]);
            }
        }

        return parent::save();
    }
}
