package ru.yandex.atom.frontend.unmarshall

import ru.yandex.atom.error.{UserProblem, UserException}
import spray.httpx.unmarshalling.Unmarshaller
import spray.http.MediaTypes._
import spray.http.HttpEntity
import spray.json.{JsArray, BasicFormats, JsonParser}

/**
 * @author avhaliullin
 */
object Unmarshalling extends BasicFormats {
  implicit val urlListUnmarshaller = Unmarshaller[Set[String]](`text/plain`, `application/json`) {
    case HttpEntity.NonEmpty(contentType, data) =>
      contentType.mediaType.value match {
        case "text/plain" => data.asString.split('\n').toSet
        case "application/json" =>
          val json = JsonParser(data.asString)
          json match {
            case JsArray(elems) => elems.map(_.convertTo[String]).toSet
            case other => throw UserException(UserProblem.MalformedRequest("JSON array expected, but found: " + data))
          }
      }
    case HttpEntity.Empty => Set()
  }
}
