<?php
namespace Teknisa\PebLibs\Controllers;

use Zeedhi\Framework\DataSource\FilterCriteria;
use Zeedhi\Framework\DTO;
use Zeedhi\Framework\DataSource\DataSet;

class ProductTree extends \Teknisa\PebLibs\Controllers\TeknisaCrud {
    //protected $dataSourceName = "product_tree";
    //protected $dataSourceName = "product_list";
    protected $dataSourceName = "produto_arvore";

    public function find(DTO\Request\Filter $request, DTO\Response $response) {
        $filterCriteria = $request->getFilterCriteria();
        $conditions     = $filterCriteria->getConditions();

        //uncomment lines when Zeedhi Framework manage to get faster
         if(count($conditions) == 1) {
            if(($conditions[0]['value'] == '%' || $conditions[0]['value'] == '%%') && $conditions[0]['operator'] == 'LIKE_ALL')
                $filterCriteria->addCondition("CDPRODNIVANTE", "IS_NULL", null);
        } 
        parent::find($request, $response);

        $dataSets = $response->getDataSets();
        $rows = $dataSets[0]->getRows();
        
         $rows = array_map(function($row) {
            $columnName = isset($row['HASCHILD'])? 'HASCHILD' : 'PAI';
            $row['_hasChild'] = $row[$columnName] === 'true' ? true : false;
            unset($row[$columnName]);
            return $row;
        }, $rows); 

        $response->setDataSets(array(new DataSet('products', $rows)));
    }
}
