<?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 Chutier entity.
 *
 * @see \Drupal\edlp_studio\Entity\Chutier.
 */
class ChutierAccessControlHandler extends EntityAccessControlHandler {

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

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

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

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

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

}
