<?php
namespace Teknisa\PebLibs\Controllers;

use Zeedhi\Framework\DataSource\Manager;
use Zeedhi\Framework\DataSource\DataSet;
use Zeedhi\Framework\DataSource\FilterCriteria;
use Zeedhi\Framework\DataSource\ParameterBag;
use Zeedhi\Framework\DTO;
use Zeedhi\Framework\DTO\Response\Message;
use Zeedhi\Framework\DTO\Response\Error;

class Paramfilial extends \Teknisa\PebLibs\Controllers\TeknisaCrud {

    protected $dataSourceName = "paramfilial";
	protected $crudService;
	protected $parameterBag;
	protected $dataSourceManager;
	protected $environment;
    protected $entityManager;

	public function __construct($crudService, ParameterBag $parameterBag, $dataSourceManager, $environment, $entityManager) {
		$this->crudService = $crudService;
        $this->parameterBag = $parameterBag;
        $this->dataSourceManager = $dataSourceManager;
        $this->environment = $environment;
        $this->entityManager = $entityManager;
	}

	public function unidadesRelacionadas(DTO\Request $request, DTO\Response $response) {
        $this->dataSourceName = 'unidadesRelacionadas';
        $this->parameterBagColumns = array("NRORG", "CDOPERADOR");

        parent::find($request, $response);

        $this->dataSourceName = 'paramfilial';
        $this->parameterBagColumns = array();
    }


    public function alterarEstrutura(DTO\Request $request, DTO\Response $response) {
        try {
            $operador = $request->getRow();
            $this->alterarEstruturaService($operador['CDFILIAL'], $this->environment->getCdoperador(), $operador['NRORG']);
            $row = array();
            $row['CDFILIAL'] = $operador['CDFILIAL'];
            $row['CDOPERADOR'] = $this->environment->getCdoperador();
            $row['NRORG'] = $operador['NRORG'];
            $dataSet = new DataSet('operador', array($row));
            $response->setDataSets(array($dataSet));
        }catch(\Exception $e) {
            $response->setError(new \Zeedhi\Framework\DTO\Response\Error($e->getMessage(), $e->getCode()));
        }
    }


    public function alterarEstruturaService($cdfilial, $cdoperador, $nrorg) {
        $operador = $this->entityManager->getRepository('\Teknisa\Model\Geral\Entities\Operador')
            ->findOneBy(
                array(
                    'cdoperador' => $cdoperador,
                    'nrorg' => $nrorg
                )
            );
        $operador->setNrorgtrab($nrorg);
        $operador->setCdfilialselecionada($cdfilial);
        $operador->setNrorgselecionada($nrorg);
        $this->entityManager->persist($operador);
        $this->entityManager->flush();
        $this->environment->setCdFilial($cdfilial);
    }
}
