<?php

namespace Drupal\edlp_studio;

use Drupal\Core\Entity\EntityAccessControlHandler;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;

/**
 * Access controller for the Composition entity.
 *
 * @see \Drupal\edlp_studio\Entity\Composition.
 */
class CompositionAccessControlHandler extends EntityAccessControlHandler {

  /**
   * {@inheritdoc}
   */
  protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
    /** @var \Drupal\edlp_studio\Entity\CompositionInterface $entity */
    switch ($operation) {
      case 'view':
        if (!$entity->isPublished()) {
          if($account->hasPermission('view own unpublished composition entities') && $account->isAuthenticated() && $account->id() == $entity->getOwnerId() ){
            return AccessResult::allowed()->cachePerPermissions()->cachePerUser()->addCacheableDependency($entity);
          }else{
            return AccessResult::allowedIfHasPermission($account, 'view any unpublished composition entities');
          }
        }
        return AccessResult::allowedIfHasPermission($account, 'view published composition entities');

      case 'update':
        if($account->hasPermission('edit own composition entities') && $account->isAuthenticated() && $account->id() == $entity->getOwnerId() ){
          return AccessResult::allowed()->cachePerPermissions()->cachePerUser()->addCacheableDependency($entity);
        }else{
          return AccessResult::allowedIfHasPermission($account, 'edit any composition entities');
        }

      case 'delete':
        if($account->hasPermission('delete own composition entities') && $account->isAuthenticated() && $account->id() == $entity->getOwnerId() ){
          return AccessResult::allowed()->cachePerPermissions()->cachePerUser()->addCacheableDependency($entity);
        }else{
          return AccessResult::allowedIfHasPermission($account, 'delete composition entities');
        }
    }

    // Unknown operation, no opinion.
    return AccessResult::neutral();
  }

  /**
   * {@inheritdoc}
   */
  protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
    return AccessResult::allowedIfHasPermission($account, 'add composition entities');
  }

}
