/**
  * Akce pro vytvoření nového uživatelského účtu na základě zaslaných hodnot
  * @SWG\Post(
  *   tags={"Miners"},
  *   path="/miners",
  *   summary="Create new miner",
  *   security={{"apiKey":{}},{"apiKeyHeader":{}}},
  *   produces={"application/json", "application/xml"},
  *   consumes={"application/json", "application/xml"},
  *   @SWG\Parameter(
  *     description="Miner",
  *     name="miner",
  *     required=true,
  *     @SWG\Schema(ref="#/definitions/MinerInput"),
  *     in="body"
  *   ),
  *   @SWG\Response(
  *     response=201,
  *     description="Miner created successfully, returns details of Miner.",
  *     @SWG\Schema(ref="#/definitions/MinerResponse")
  *   ),
  *   @SWG\Response(
  *     response=422,
  *     description="Sent values are not acceptable!",
  *     @SWG\Schema(ref="#/definitions/InputErrorResponse")
  *   )
  * )
  */
 public function actionCreate()
 {
     //prepare Miner from input values
     /** @var Miner $miner */
     $miner = new Miner();
     /** @var array $data */
     $data = $this->input->getData();
     $miner->name = $data['name'];
     $miner->type = $data['type'];
     $miner->datasource = $this->datasource;
     if (!empty($this->ruleSet)) {
         $miner->ruleSet = $this->ruleSet;
     }
     $miner->created = new \DateTime();
     $miner->user = $this->getCurrentUser();
     $this->minersFacade->saveMiner($miner);
     $metasourceTask = $this->metasourcesFacade->startMinerMetasourceInitialization($miner, $this->minersFacade);
     while ($metasourceTask && $metasourceTask->state != MetasourceTask::STATE_DONE) {
         $metasourceTask = $this->metasourcesFacade->initializeMinerMetasource($miner, $metasourceTask);
         usleep(100);
     }
     $this->metasourcesFacade->deleteMetasourceTask($metasourceTask);
     //send response
     $this->actionRead($miner->minerId);
 }
 /**
  * Akce pro vytvoření nového atributu
  * @SWG\Post(
  *   tags={"Attributes"},
  *   path="/attributes",
  *   summary="Create new attribute using defined preprocessing",
  *   consumes={"application/json","application/xml"},
  *   produces={"application/json","application/xml"},
  *   security={{"apiKey":{}},{"apiKeyHeader":{}}},
  *   @SWG\Parameter(
  *     description="New attribute",
  *     name="body",
  *     required=true,
  *     @SWG\Schema(ref="#/definitions/NewAttributeInput"),
  *     in="body"
  *   ),
  *   @SWG\Response(
  *     response=201,
  *     description="Attribute created",
  *     @SWG\Schema(
  *       ref="#/definitions/AttributeResponse"
  *     )
  *   ),
  *   @SWG\Response(
  *     response=400,
  *     description="Invalid API key supplied",
  *     @SWG\Schema(ref="#/definitions/StatusResponse")
  *   )
  * )
  * @throws \InvalidArgumentException
  */
 public function actionCreate()
 {
     /** @var array $inputData */
     $inputData = $this->input->getData();
     $miner = $this->findMinerWithCheckAccess(@$inputData['miner']);
     $this->minersFacade->checkMinerMetasource($miner);
     $currentUser = $this->getCurrentUser();
     //aktualizace informace o datových sloupcích
     $this->datasourcesFacade->updateDatasourceColumns($miner->datasource, $currentUser);
     try {
         if (!empty($inputData['column'])) {
             $datasourceColumn = $this->datasourcesFacade->findDatasourceColumn($miner->datasource, @$inputData['column']);
         } else {
             $datasourceColumn = $this->datasourcesFacade->findDatasourceColumnByName($miner->datasource, @$inputData['columnName']);
         }
     } catch (\Exception $e) {
         throw new InvalidArgumentException("Datasource columns was not found: " . @$inputData['columnName']);
     }
     //inicializace formátu
     $format = $datasourceColumn->format;
     if (!$format) {
         //TODO implementovat podporu automatického mapování
         $format = $this->metaAttributesFacade->simpleCreateMetaAttributeWithFormatFromDatasourceColumn($datasourceColumn, $currentUser);
         $datasourceColumn->format = $format;
         $this->datasourcesFacade->saveDatasourceColumn($datasourceColumn);
     }
     //vytvoření nového atributu
     $attribute = new Attribute();
     $attribute->metasource = $miner->metasource;
     $attribute->datasourceColumn = $datasourceColumn;
     $attribute->name = $this->minersFacade->prepareNewAttributeName($miner, $inputData['name']);
     $attribute->type = $attribute->datasourceColumn->type;
     if (@$inputData['specialPreprocessing'] == Preprocessing::SPECIALTYPE_EACHONE) {
         $preprocessing = $this->metaAttributesFacade->findPreprocessingEachOne($datasourceColumn->format);
         $attribute->preprocessing = $preprocessing;
     } else {
         throw new \BadMethodCallException('Selected preprocessing type is not supported.');
         //FIXME je nutné nalézt příslušný preprocessing...
     }
     $attribute->active = false;
     $this->metasourcesFacade->saveAttribute($attribute);
     //inicializace preprocessingu
     $metasourceTask = $this->metasourcesFacade->startAttributesPreprocessing($miner->metasource, [$attribute]);
     while ($metasourceTask && $metasourceTask->state != MetasourceTask::STATE_DONE) {
         $metasourceTask = $this->metasourcesFacade->preprocessAttributes($metasourceTask);
     }
     //smazání předzpracovávací úlohy
     $this->metasourcesFacade->deleteMetasourceTask($metasourceTask);
     $this->setXmlMapperElements('attribute');
     $this->resource = $attribute->getDataArr();
     $this->sendResource();
 }
 /**
  * Akce vracející data description a konfiguraci pro EasyMiner UI
  * @param int $id_dm
  * @param int $miner
  * @throws ForbiddenRequestException
  */
 public function actionGetData($id_dm, $miner)
 {
     if (empty($miner)) {
         $miner = $id_dm;
     }
     //------------------------------------------------------------------------------------------------------------------
     $miner = $this->findMinerWithCheckAccess($miner);
     $minerType = $miner->type;
     $FLPathElement = 'FLPath_' . Strings::upper($minerType);
     //------------------------------------------------------------------------------------------------------------------
     #region připravení informací pro UI - s odděleným připravením DataDictionary
     $dataDescriptionPMML = null;
     $dataParser = new DataParser($dataDescriptionPMML, $this->config->{$FLPathElement}, $this->config->FGCPath, null, null, $this->translator->getLang());
     $dataParser->loadData();
     $responseContent = $dataParser->parseData();
     $user = $this->getCurrentUser();
     $responseContent['DD'] = ['dataDictionary' => $this->datasourcesFacade->exportDataDictionaryArr($miner->datasource, $user, $rowsCount), 'transformationDictionary' => $this->metasourcesFacade->exportTransformationDictionaryArr($miner->metasource, $user), 'recordCount' => $rowsCount];
     #endregion připravení informací pro UI - s odděleným připravením DataDictionary
     uksort($responseContent['DD']['transformationDictionary'], function ($a, $b) {
         return strnatcasecmp($a, $b);
     });
     uksort($responseContent['DD']['dataDictionary'], function ($a, $b) {
         return strnatcasecmp($a, $b);
         //return strnatcasecmp(mb_strtolower($a,'utf-8'),mb_strtolower($b,'utf-8'));
     });
     $responseContent['status'] = 'ok';
     $responseContent['miner_type'] = $miner->type;
     $responseContent['miner_name'] = $miner->name;
     if ($miner->ruleSet) {
         $ruleSet = $miner->ruleSet;
     } else {
         $ruleSet = $this->ruleSetsFacade->saveNewRuleSetForUser($miner->name, $this->getCurrentUser());
         $miner->ruleSet = $ruleSet;
         $this->minersFacade->saveMiner($miner);
     }
     $responseContent['miner_ruleset'] = ['id' => $ruleSet->ruleSetId, 'name' => $ruleSet->name];
     $responseContent['miner_config'] = $miner->getExternalConfig();
     $this->sendJsonResponse($responseContent);
 }
 /**
  * Funkce vracející formulář pro vytvoření atributu na základě vybraného sloupce a preprocessingu
  * @return Form
  */
 protected function createComponentNewAttributeForm()
 {
     $form = new Form();
     $presenter = $this;
     $form->setTranslator($this->translator);
     $form->addHidden('miner');
     $form->addHidden('column');
     $form->addHidden('preprocessing');
     $form->addText('attributeName', 'Attribute name:')->setRequired('Input attribute name!')->addRule(Form::PATTERN, 'Attribute name can contain only letters, numbers and _ and has start with a letter.', '[a-zA-Z]{1}\\w*')->addRule(function (TextInput $input) {
         //kontrola, jestli již existuje atribtu se zadaným názvem
         $values = $input->getForm(true)->getValues();
         $miner = $this->findMinerWithCheckAccess($values->miner);
         $attributes = $miner->metasource->attributes;
         if (!empty($attributes)) {
             foreach ($attributes as $attribute) {
                 if ($attribute->name == $input->value) {
                     return false;
                 }
             }
         }
         return true;
     }, 'Attribute with this name already exists!');
     $form->addSubmit('submit', 'Create attribute')->onClick[] = function (SubmitButton $button) {
         $values = $button->form->values;
         $miner = $this->findMinerWithCheckAccess($values->miner);
         $this->minersFacade->checkMinerMetasource($miner);
         $attribute = new Attribute();
         $attribute->metasource = $miner->metasource;
         $attribute->datasourceColumn = $this->datasourcesFacade->findDatasourceColumn($miner->datasource, $values->column);
         $attribute->name = $values->attributeName;
         $attribute->type = $attribute->datasourceColumn->type;
         $attribute->preprocessing = $this->metaAttributesFacade->findPreprocessing($values->preprocessing);
         $attribute->active = false;
         $this->metasourcesFacade->saveAttribute($attribute);
         $metasourceTask = $this->metasourcesFacade->startAttributesPreprocessing($miner->metasource, [$attribute]);
         $this->redirect('preprocessingTask', ['id' => $metasourceTask->metasourceTaskId]);
     };
     $storno = $form->addSubmit('storno', 'storno');
     $storno->setValidationScope(array());
     $storno->onClick[] = function (SubmitButton $button) use($presenter) {
         //přesměrování na výběr preprocessingu
         $values = $button->form->getValues();
         $presenter->redirect('addAttribute', array('column' => $values->column, 'miner' => $values->miner));
     };
     return $form;
 }
 /**
  * Akce pro otevření existujícího mineru
  * @param int $id
  * @throws BadRequestException
  */
 public function actionOpenMiner($id)
 {
     $miner = $this->findMinerWithCheckAccess($id);
     if (!$miner->metasource) {
         //přesměrování na skript přípravy metasource...
         $this->redirect('initMiner', ['id' => $id]);
         return;
     } else {
         //kontrola stavu metasource...
         $metasource = $miner->metasource;
         if (!empty($metasource->metasourceTasks)) {
             $metasourceTasks = $metasource->metasourceTasks;
             foreach ($metasourceTasks as $metasourceTask) {
                 if ($metasourceTask->type == MetasourceTask::TYPE_INITIALIZATION) {
                     //přesměrování na skript přípravy metasource...
                     $this->redirect('initMiner', ['id' => $id]);
                     return;
                 } elseif ($metasourceTask->type == MetasourceTask::TYPE_PREPROCESSING && !empty($metasourceTask->attributes)) {
                     //TODO nutnost přesměrování na inicializaci atributů
                 }
             }
         }
         $attributesCount = count($metasource->attributes);
         try {
             $this->metasourcesFacade->checkMetasourceState($metasource);
         } catch (\Exception $e) {
             if (!$attributesCount == 0) {
                 $this->metasourcesFacade->deleteMetasource($metasource);
                 $this->redirect('initMiner', ['id' => $id]);
             } else {
                 throw new InvalidStateException('Requested miner is not available! (metasource error)', $e);
             }
         }
     }
     //zaktualizujeme info o posledním otevření mineru
     $miner->lastOpened = new \DateTime();
     $this->minersFacade->saveMiner($miner);
     $this->redirect('MiningUi:', ['id' => $miner->minerId]);
 }