<?php

namespace Teknisa\Libs\Util\Log;

use Teknisa\Libs\Util\Repositories\ZhuLog as ZhuLogRepository;
use Teknisa\Libs\Util\Utilities;
use Teknisa\Libs\Util\InstanceProvider;

class ZhuLogProvider implements ZhuLog {
    /** @var ZhuLogRepository $zhuLogRepository */
    protected $zhuLogRepository;

    /**
     * @param ZhuLogRepository $zhuLogRepository
     */
    public function __construct(ZhuLogRepository $zhuLogRepository) {
        $this->zhuLogRepository = $zhuLogRepository;
    }

    /**
     * @param $conditions
     * @param Number $page
     * @param $pageSize
     * @param $orderBy
     * @return array
     */
    public function find($conditions, $page, $pageSize, $orderBy) {
        $filters = '';
        foreach($conditions as $key => &$filter) {
            if ($filter['columnName'] == 'ROUTE_LABEL') {
                $filter['columnName'] = 'ROUTE';
            } else if ($filter['columnName'] == 'TYPE') {
                $filters .= " AND " . $filter['columnName'] . $filter['operator'] . "'" . $filter['value'] . "'";
                unset($conditions[$key]);
            }
        }
        $filters .= Utilities::NRORG_FILTER_ZHU_LOG . InstanceProvider::getEnvironment()->getNrOrg();
        $defaultFilters = Utilities::createQueryFiltered($conditions, null, true);
        $limit = $page * $pageSize;
        $offset = ($page - 1) * $pageSize;
        $qryOrder = '';
        $firstOrderBy = true;
        if(empty($orderBy)) {
            $qryOrder .= ' ORDER BY TIMESTAMP DESC, ROUTE';
        } else {
            foreach ($orderBy as $idx => $order) {
                $ob = $firstOrderBy ? ' ORDER BY ' : ',';
                $qryOrder .= $ob . $idx . ' ' . $order;
                $firstOrderBy = false;
            }
        }
        return $this->zhuLogRepository->getZhuLog($filters . $defaultFilters, $limit, $offset, Utilities::getProjectIdParameter(), $qryOrder);
    }
} 