/**
   * Allows the user to remove a storage system from the list of decommisioned resources After that
   * corresponding provider should be able to be rescanned and add this system back to the list of
   * managed systems.
   *
   * @param id id the URN of a ViPR Storage provider
   * @param param The storage system details.
   * @brief removes the storage system from the list of decommissioned systems and rescans the
   *     provider.
   * @return An asynchronous task corresponding to the scan job scheduled for the provider.
   * @throws BadRequestException When the system type is not valid or a storage system with the same
   *     native guid already exists.
   * @throws com.emc.storageos.db.exceptions.DatabaseException When an error occurs querying the
   *     database.
   * @throws ControllerException When an error occurs discovering the storage system.
   */
  @PUT
  @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  @CheckPermission(roles = {Role.SYSTEM_ADMIN})
  @Path("/{id}/storage-systems")
  public TaskResourceRep addStorageSystem(
      @PathParam("id") URI id, StorageSystemProviderRequestParam param) throws ControllerException {
    TaskResourceRep taskRep;
    URIQueryResultList list = new URIQueryResultList();

    ArgValidator.checkFieldNotEmpty(param.getSystemType(), "system_type");
    if (!StorageSystem.Type.isProviderStorageSystem(
        DiscoveredDataObject.Type.valueOf(param.getSystemType()))) {
      throw APIException.badRequests.cannotAddStorageSystemTypeToStorageProvider(
          param.getSystemType());
    }

    StorageProvider provider = _dbClient.queryObject(StorageProvider.class, id);
    ArgValidator.checkEntityNotNull(provider, id, isIdEmbeddedInURL(id));

    ArgValidator.checkFieldNotEmpty(param.getSerialNumber(), "serialNumber");

    String nativeGuid =
        NativeGUIDGenerator.generateNativeGuid(param.getSystemType(), param.getSerialNumber());
    // check for duplicate StorageSystem.

    List<StorageSystem> systems =
        CustomQueryUtility.getActiveStorageSystemByNativeGuid(_dbClient, nativeGuid);
    if (systems != null && !systems.isEmpty()) {
      throw APIException.badRequests.invalidParameterProviderStorageSystemAlreadyExists(
          "nativeGuid", nativeGuid);
    }

    int cleared =
        DecommissionedResource.removeDecommissionedFlag(_dbClient, nativeGuid, StorageSystem.class);
    if (cleared == 0) {
      log.info("Cleared {} decommissioned systems", cleared);
    } else {
      log.info("Did not find any decommissioned systems to clear. Continue to scan.");
    }

    ArrayList<AsyncTask> tasks = new ArrayList<AsyncTask>(1);
    String taskId = UUID.randomUUID().toString();
    tasks.add(new AsyncTask(StorageProvider.class, provider.getId(), taskId));

    BlockController controller = getController(BlockController.class, provider.getInterfaceType());
    DiscoveredObjectTaskScheduler scheduler =
        new DiscoveredObjectTaskScheduler(_dbClient, new ScanJobExec(controller));
    TaskList taskList = scheduler.scheduleAsyncTasks(tasks);
    return taskList.getTaskList().listIterator().next();
  }
  /**
   * Vcenter Discovery
   *
   * @param vcenter the Vcenter to be discovered. provided, a new taskId is generated.
   * @return the task used to track the discovery job
   */
  protected TaskResourceRep doDiscoverVcenter(Vcenter vcenter) {
    ComputeSystemController controller = getController(ComputeSystemController.class, "vcenter");
    DiscoveredObjectTaskScheduler scheduler =
        new DiscoveredObjectTaskScheduler(_dbClient, new DiscoverJobExec(controller));
    String taskId = UUID.randomUUID().toString();
    ArrayList<AsyncTask> tasks = new ArrayList<AsyncTask>(1);
    tasks.add(new AsyncTask(Vcenter.class, vcenter.getId(), taskId));

    TaskList taskList = scheduler.scheduleAsyncTasks(tasks);

    TaskResourceRep taskResourceRep = taskList.getTaskList().iterator().next();
    updateTaskTenant(taskResourceRep);

    return taskResourceRep;
  }
 /**
  * Scan all Storage providers.
  *
  * @brief Scan Storage providers
  * @return TasList of all created asynchronous tasks
  */
 @POST
 @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
 @CheckPermission(roles = {Role.SYSTEM_ADMIN, Role.RESTRICTED_SYSTEM_ADMIN})
 @Path("/scan")
 public TaskList scanStorageProviders() {
   TaskList taskList = new TaskList();
   List<URI> providerURIList = _dbClient.queryByType(StorageProvider.class, true);
   /** TODO needs to remove hard code device type to fetch the controller instance */
   BlockController controller = getController(BlockController.class, "vnxblock");
   DiscoveredObjectTaskScheduler scheduler =
       new DiscoveredObjectTaskScheduler(_dbClient, new ScanJobExec(controller));
   ArrayList<AsyncTask> tasks = new ArrayList<AsyncTask>();
   if (providerURIList != null) {
     for (URI providerURI : providerURIList) {
       String taskId = UUID.randomUUID().toString();
       tasks.add(new AsyncTask(StorageProvider.class, providerURI, taskId));
     }
     taskList = scheduler.scheduleAsyncTasks(tasks);
   }
   return taskList;
 }
  @POST
  @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  @CheckPermission(roles = {Role.SYSTEM_ADMIN, Role.RESTRICTED_SYSTEM_ADMIN})
  public TaskResourceRep registerStorageProvider(StorageProviderCreateParam param)
      throws ControllerException {
    ArgValidator.checkFieldNotEmpty(param.getName(), "name");
    checkForDuplicateName(param.getName(), StorageProvider.class);

    ArgValidator.checkFieldNotEmpty(param.getIpAddress(), "ip_address");
    ArgValidator.checkFieldNotNull(param.getPortNumber(), "port_number");
    ArgValidator.checkFieldNotEmpty(param.getUserName(), "user_name");
    ArgValidator.checkFieldNotEmpty(param.getPassword(), "password");
    ArgValidator.checkFieldRange(param.getPortNumber(), 1, 65535, "port_number");
    ArgValidator.checkFieldValueFromEnum(
        param.getInterfaceType(), "interface_type", StorageProvider.InterfaceType.class);
    String providerKey = param.getIpAddress() + "-" + param.getPortNumber();
    List<StorageProvider> providers =
        CustomQueryUtility.getActiveStorageProvidersByProviderId(_dbClient, providerKey);
    if (providers != null && !providers.isEmpty()) {
      throw APIException.badRequests.invalidParameterStorageProviderAlreadyRegistered(providerKey);
    }

    // Set the SSL parameter
    Boolean useSSL = param.getUseSSL();
    if (useSSL == null) {
      useSSL = StorageProviderCreateParam.USE_SSL_DEFAULT;
    }

    StorageProvider provider = new StorageProvider();
    provider.setId(URIUtil.createId(StorageProvider.class));
    provider.setLabel(param.getName());
    provider.setIPAddress(param.getIpAddress());
    provider.setPortNumber(param.getPortNumber());
    provider.setUserName(param.getUserName());
    provider.setPassword(param.getPassword());
    provider.setUseSSL(useSSL);
    provider.setInterfaceType(param.getInterfaceType());
    provider.setRegistrationStatus(RegistrationStatus.REGISTERED.toString());
    provider.setConnectionStatus(ConnectionStatus.INITIALIZING.name());
    provider.setSecondaryUsername(param.getSecondaryUsername());
    provider.setSecondaryPassword(param.getSecondaryPassword());
    provider.setElementManagerURL(param.getElementManagerURL());
    if (param.getSioCLI() != null) {
      // TODO: Validate the input?
      provider.addKey(StorageProvider.GlobalKeys.SIO_CLI.name(), param.getSioCLI());
    }

    if (StorageProvider.InterfaceType.ibmxiv.name().equalsIgnoreCase(provider.getInterfaceType())) {
      provider.setManufacturer("IBM");
    }

    _dbClient.createObject(provider);

    auditOp(
        OperationTypeEnum.REGISTER_STORAGEPROVIDER,
        true,
        null,
        provider.getLabel(),
        provider.getId().toString(),
        provider.getIPAddress(),
        provider.getPortNumber(),
        provider.getUserName(),
        provider.getInterfaceType());

    ArrayList<AsyncTask> tasks = new ArrayList<AsyncTask>(1);
    String taskId = UUID.randomUUID().toString();
    tasks.add(new AsyncTask(StorageProvider.class, provider.getId(), taskId));

    BlockController controller = getController(BlockController.class, provider.getInterfaceType());
    log.debug("controller.getClass().getName() :{}", controller.getClass().getName());
    log.debug("controller.getClass().getSimpleName() :{}", controller.getClass().getSimpleName());
    /**
     * Creates MonitoringJob token for vnxblock/vmax, hds, cinder and IBM XIV device on zooKeeper
     * queue
     */
    // TODO : If all interface types have monitoring impl class added (scaleIO is missing),
    // this check can be removed.
    String interfaceType = provider.getInterfaceType();
    if (StorageProvider.InterfaceType.hicommand.name().equalsIgnoreCase(interfaceType)
        || StorageProvider.InterfaceType.smis.name().equalsIgnoreCase(interfaceType)
        || StorageProvider.InterfaceType.cinder.name().equalsIgnoreCase(interfaceType)
        || StorageProvider.InterfaceType.ibmxiv.name().equalsIgnoreCase(interfaceType)) {
      controller.startMonitoring(
          new AsyncTask(StorageProvider.class, provider.getId(), taskId),
          getSystemTypeByInterface(interfaceType));
    }

    DiscoveredObjectTaskScheduler scheduler =
        new DiscoveredObjectTaskScheduler(_dbClient, new ScanJobExec(controller));
    TaskList taskList = scheduler.scheduleAsyncTasks(tasks);
    return taskList.getTaskList().listIterator().next();
  }