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

class SavePrivileges extends PrivilegeAction
{
  protected function action()
  {
    $dbwWpt = new DBWorkWebPrivilegesT(1, true);
    $originalPrivilegesTemplates = ArrayOperations::setAttributAsKey($dbwWpt->getAll(), 'id');
    $changedPrivilegesTemplates = $this->getChangedPrivilegesTemplates($originalPrivilegesTemplates);
    if (count($changedPrivilegesTemplates) == 0) {
      return self::NO_CHANGE;
    }

    return WebPrivilegesTAPI::updateWebPrivilegesT($changedPrivilegesTemplates, $originalPrivilegesTemplates);
  }

  private function getChangedPrivilegesTemplates($privelegesTemplates)
  {
    $getAccessById = $this->createAccessByIdFunction(true);
    $changedDatamodule = array();
    foreach ($privelegesTemplates as $pt) {
      $postPrvilegAccess = $getAccessById($pt->id);
      if (!is_null($postPrvilegAccess) && $postPrvilegAccess != $pt->accessnumber) {
        $newPt = clone $pt;
        $newPt->accessnumber = $postPrvilegAccess;
        $changedDatamodule[$pt->id] = $newPt;
      }
    }

    return $changedDatamodule;
  }
}