// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

#include "azure/keyvault/administration/backup_operation.hpp"

#include "azure/keyvault/administration/backup_client.hpp"

using namespace Azure::Security::KeyVault::Administration;
using namespace Azure::Security::KeyVault::Administration::Models;

std::unique_ptr<Azure::Core::Http::RawResponse> BackupOperation::PollInternal(
    Azure::Core::Context const& context)
{
  std::unique_ptr<Azure::Core::Http::RawResponse> rawResponse;
  try
  {
    Azure::Response<BackupOperationStatus> response = m_isBackupOperation
        ? m_backupClient->FullBackupStatus(m_continuationToken, context)
        : m_backupClient->RestoreStatus(m_continuationToken, context);

    m_value = response.Value;
    m_continuationToken = response.Value.JobId;
    rawResponse = std::move(response.RawResponse);
    if (response.Value.Status == "InProgress")
    {
      m_status = Azure::Core::OperationStatus::Running;
    }
    else if (response.Value.Status == "Succeeded")
    {
      m_status = Azure::Core::OperationStatus::Succeeded;
    }
    else if (response.Value.Status == "Failed")
    {
      m_status = Azure::Core::OperationStatus::Failed;
    }
    else
    {
      throw Azure::Core::RequestFailedException(response.RawResponse);
    }
  }
  catch (Azure::Core::RequestFailedException& error)
  {
    rawResponse = std::move(error.RawResponse);
  }

  return rawResponse;
}

Azure::Response<BackupOperationStatus> BackupOperation::PollUntilDoneInternal(
    std::chrono::milliseconds period,
    Azure::Core::Context& context)
{
  while (true)
  {
    // Poll will update the raw response.
    Poll(context);
    if (IsDone())
    {
      break;
    }
    std::this_thread::sleep_for(period);
  }

  return Azure::Response<BackupOperationStatus>(
      m_value, std::make_unique<Azure::Core::Http::RawResponse>(*m_rawResponse));
}
