package ru.yandex.featurer.controller

import org.slf4j.LoggerFactory
import ru.yandex.autodoc.common.doc.params.ParamType
import ru.yandex.autodoc.spray.rest._
import ru.yandex.autodoc.spray.rest.req.RestParam
import ru.yandex.featurer.data.{AppId, FeatureId}
import ru.yandex.featurer.service._

import scala.util.Success

/**
 * @author avhaliullin
 */
trait ControllersComponent {
  component: OperationsServiceComponent =>

  private val log = LoggerFactory.getLogger(classOf[ControllersComponent])

  private def appIdParam(name: String) = RestParam(name, "id приложения", ParamType.STRING, s => Success(AppId(s)))

  private def featureIdParam(name: String) = RestParam(name, "имя бранча", ParamType.STRING, s => Success(FeatureId(s)))

  def restHandle = rest("applications") alternatives(
    _ get "Список всех приложений" apply {
      () =>
        operationsService.listApplications
    },
    _ / "checkAll" post "Обновить все пакеты" apply {
      () =>
        operationsService.updateAll()
    },
    _ / appIdParam("appId") alternatives(
      _ get "Информация о приложении" apply {
        appId =>
          operationsService.getApplicationInfo(appId)
      },
      _ / "features" alternatives(
        _ get "Список фич" apply {
          appId =>
            operationsService.listAppFeatures(appId)
        },
        _ / featureIdParam("featureId") alternatives(
          _ get "Информация о фиче" apply {
            (appId, featureId) =>
              operationsService.getApplicationFeatureInfo(appId, featureId)
          },
          _ / "create" post "Создать контейнер для фичи" apply {
            (appId, featureId) =>
              operationsService.createFeature(appId, featureId)
          },
          _ / "destroy" post "Удалить контейнер для фичи" apply {
            (appId, featureId) =>
              operationsService.deleteFeature(appId, featureId)
          },
          _ / "install" post "" apply {
            (appId, featureId) =>
              operationsService.installApplication(appId, featureId)
          }
          )
        )
      )
    )
}
