from flask import request

from data.database import configure

from config_app.c_app import app, config_provider
from config_app.config_endpoints.api import resource, ApiResource, nickname, kubernetes_only
from config_app.config_util.k8saccessor import KubernetesAccessorSingleton


@resource('/v1/kubernetes/deployments/')
class SuperUserKubernetesDeployment(ApiResource):
  """ Resource for the getting the status of Quay Enterprise deployments and cycling them """
  schemas = {
    'ValidateDeploymentNames': {
      'type': 'object',
      'description': 'Validates deployment names for cycling',
      'required': [
        'deploymentNames'
      ],
      'properties': {
        'deploymentNames': {
          'type': 'array',
          'description': 'The names of the deployments to cycle'
        },
      },
    }
  }

  @kubernetes_only
  @nickname('scGetNumDeployments')
  def get(self):
    return KubernetesAccessorSingleton.get_instance().get_qe_deployments()

  @kubernetes_only
  @nickname('scCycleQEDeployments')
  def put(self):
    deployment_names = request.get_json()['deploymentNames']
    return KubernetesAccessorSingleton.get_instance().cycle_qe_deployments(deployment_names)


@resource('/v1/superuser/config/kubernetes')
class SuperUserKubernetesConfiguration(ApiResource):
  """ Resource for saving the config files to kubernetes secrets. """

  @kubernetes_only
  @nickname('scDeployConfiguration')
  def post(self):
    return config_provider.save_configuration_to_kubernetes()


@resource('/v1/kubernetes/config/populate')
class KubernetesConfigurationPopulator(ApiResource):
  """ Resource for populating the local configuration from the cluster's kubernetes secrets. """

  @kubernetes_only
  @nickname('scKubePopulateConfig')
  def post(self):
    # Get a clean transient directory to write the config into
    config_provider.new_config_dir()
    KubernetesAccessorSingleton.get_instance().save_secret_to_directory(config_provider.get_config_dir_path())

    # We update the db configuration to connect to their specified one
    # (Note, even if this DB isn't valid, it won't affect much in the config app, since we'll report an error,
    # and all of the options create a new clean dir, so we'll never pollute configs)
    combined = dict(**app.config)
    combined.update(config_provider.get_config())
    configure(combined)

    return 200