package com.cloudhandson.vpdbackoffice.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Service;

/**
 * Keeps user/role/permission services independent from optional external
 * authorization runtimes. The normal VPD application can run without a
 * synchronizer; if one exists, it receives the change before the management
 * request returns.
 */
@Service
public class ExternalAuthorizationChangeNotifier {

  private static final Logger log = LoggerFactory.getLogger(ExternalAuthorizationChangeNotifier.class);
  private final ObjectProvider<ExternalAuthorizationSynchronizer> synchronizer;

  public ExternalAuthorizationChangeNotifier(ObjectProvider<ExternalAuthorizationSynchronizer> synchronizer) {
    this.synchronizer = synchronizer;
  }

  private ExternalAuthorizationChangeNotifier() {
    this.synchronizer = null;
  }

  public static ExternalAuthorizationChangeNotifier noop() {
    return new ExternalAuthorizationChangeNotifier();
  }

  public void changed(String reason) {
    if (synchronizer != null) {
      ExternalAuthorizationSynchronizer target = synchronizer.getIfAvailable();
      if (target != null) {
        log.info("External authorization change synchronized: {}", reason);
        target.synchronize(reason);
      }
    }
  }
}
