<?php namespace App\Utils\Collections;

use App\DAO\Order\QueryOrder;

class QueryOrderCollection extends GeneralCollection
{
    public function __construct(array $query_string=[], array $translator=[])
    {
        $sort = $query_string['sort'];
        if ($sort) {
            $desc = $sort[0] === '-';
            $sort = preg_replace('/[+-]/','', $sort);
            if ($translator[$sort]) {
                $this->push(QueryOrder::builder()
                    ->setDesc($desc)
                    ->setNameParam($sort)
                    ->setTable($translator[$sort]['table'])
                    ->build()
                );
            }
        }
    }

    public function generateSQL () : string {
        if ($this->length > 0) {
            $order_by_string = ' ORDER BY ';
            $this->forEach(function (QueryOrder $queryOrder, int $index) use (&$order_by_string) {
                $separator = $index === 0 ? ' ' : ',';
                $order_by_string .= "$separator{$queryOrder->getTable()}.`{$queryOrder->getNameParam()}` {$queryOrder->calculateOrderWay()}";
            });
            return $order_by_string;
        } else {
            return '';
        }
    }
}