<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

namespace Kufer\KuferTools\Utils;

class WssInFiles
{
  
  public function getWss($sightId, $user = null)
  {
    $pathToFile = $this->getPath4Get($sightId);

    return $this->getWssFromFile($pathToFile, $sightId, $user);
  }

  
  public function saveWss($sightId, $wssAry)
  {
    $pathToFile = $this->getPath4Save($sightId);

    return $this->saveWssToFile($pathToFile, $wssAry);
  }

  private function getPath4Save($sightId)
  {
    if (DEVELOP) {
      return $this->getPathSysFolder($sightId);
    } else {
      $file = $this->getPathUserFolder($sightId);
      $dir = \dirname($file);
      \FSOperations::mkDir($dir);

      return $file;
    }
  }

  private function getPath4Get($sightId)
  {
    if (DEVELOP) {
      return $this->getPathSysFolder($sightId);
    } else {
      $pathToFile = $this->getPathUserFolder($sightId);
      if (file_exists($pathToFile)) {
        return $pathToFile;
      } else {
        return $this->getPathSysFolder($sightId);
      }
    }
  }

  private function getPathSysFolder($sightId)
  {
    return BASEDIR . '/kufertools/settings/sys/' . $this->getRelativeFilePath($sightId);
  }

  private function getPathUserFolder($sightId)
  {
    if (\SessionOperations::isPreviewMode()) {
      return BASEDIR . '/kufertools/settings/user/preview/' . $this->getRelativeFilePath($sightId);
    }

    return BASEDIR . '/kufertools/settings/user/' . $this->getRelativeFilePath($sightId);
  }

  private function getRelativeFilePath($sightId)
  {
    return 'layout/wss/wss-' . $sightId . '.wss';
  }

  
  private function getWssFromFile($pathToFile, $pSightId, $user = null)
  {
    if (file_exists($pathToFile)) {
      $wssBase64 = file_get_contents($pathToFile);

      
      $encodingstr = 'ENCODING=';
      if (\StringOperations::startsWith($wssBase64, $encodingstr)) {
        $encodingstrlen = \StringOperations::strlen($encodingstr, 'ASCII');
        $encodingendpos = \StringOperations::strpos($wssBase64, '#', $encodingstrlen, 'ASCII');
        $wssBase64 = \StringOperations::substr($wssBase64, $encodingendpos + 1, null, 'ASCII');
      }

      $wssAry = \SerializeOperations::unserialize($wssBase64);
      if (is_array($wssAry)) {
        $filledAry = $this->fillWssAryWithAdditionalInfos($wssAry, $user);
        if (empty($filledAry)) {
          \Logger::logg('Die Rechtevorlage zu aktuellen Tool fehlt oder alle Rechte für die aktuelle Sicht ' . $pSightId
              . ' sind gesperrt', 250);
        }

        return $filledAry;
      }
    }

    return array();
  }

  
  private function fillWssAryWithAdditionalInfos($wssAry, $user = null)
  {
    $dbwWsf = new \DBWorkSightsFields(1, true);

    $sightFieldIds = \ArrayOperations::mapAttribut($wssAry, 'sight_field_id');
    $sightFields = $dbwWsf->getFieldByIds($sightFieldIds);
    $sightFieldIdsGruppiert = \ArrayOperations::setAttributAsKey($sightFields, 'id');

    $wssFactory = new \Kufer\KuferTools\Utils\WssField\WssFactory();

    foreach ($wssAry as $key => $wss) {
      if (!isset($sightFieldIdsGruppiert[$wss->sight_field_id]) || $sightFieldIdsGruppiert[$wss->sight_field_id]->id < 1) {
        unset($wssAry[$key]);

        continue;
      } else {
        $wsf = $sightFieldIdsGruppiert[$wss->sight_field_id];
      }

      $tmpbool = 2;
      if (!is_null($user) && !$user->isEmpty()) {
        $tmpbool = \SecurityOperations::privilegAllowed(
          $user->getIdentifier(),
          $wsf->tool_id,
          $wsf->privileg_key
        );
        if ($tmpbool == 0) {
          unset($wssAry[$key]);

          continue;
        }
      }

      self::setWssFromWsf($wss, $wsf, $tmpbool);

      $wssField = $wssFactory->getWss($wss);
      $wssAry[$key] = $wssField->getDmColumnMitDefaultBeruecksichtigt();
    }
    
    return array_values($wssAry);
  }

  protected static function setWssFromWsf($wss, $wsf, $tmpboolAccessLevel)
  {
    $wss->field_id = $wsf->field_id;
    $wss->privileg_id = $wsf->privileg_id;
    $wss->istext = $wsf->istext;
    $wss->canedit = $wsf->canedit && $tmpboolAccessLevel >= 2;
    $wss->name = $wsf->name;
    $wss->fieldname = $wsf->fieldname;
    $wss->datamodul = $wsf->datamodul;
    $wss->fieldgroup = $wsf->fieldgroup;
    $wss->privileg_key = $wsf->privileg_key;
    $wss->accesslevel = $tmpboolAccessLevel;

    return $wss;
  }

  private function saveWssToFile($pathToFile, $wssAry)
  {
    $wssBase64 = \SerializeOperations::serialize4Settings($wssAry);
    
    
    return file_put_contents($pathToFile, $wssBase64);
  }
}