package org.protozoo.server.repo

import org.osgi.service.component.annotations.*
import org.protozoo.server.api.RestService
import org.protozoo.system.repo.Repository
import javax.ws.rs.GET
import javax.ws.rs.OPTIONS
import javax.ws.rs.Produces
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response


/**
 * This REST service represents the Protozoo
 * component repository and only gets activated
 * when the reference can be resolved
 */
@Component(
        name = "RepositoryResource",
        service = arrayOf(RestService),
        scope = ServiceScope.PROTOTYPE,
        enabled = true,
        immediate = false
)
@Produces(MediaType.APPLICATION_JSON)
class RepoResource : RestService {

    private var repo: Repository? = null

    @GET
    fun getAll(): Response {

        println("Components: " + this + ", " + this.repo)
        if (repo != null) {
            return Response
                    .ok()
                    .entity(repo?.getAll())
                    .header("Access-Control-Allow-Origin", "*")
                    .build()
        } else {
            return Response
                    .serverError()
                    .entity("Repository not initialized")
                    .build()
        }
    }

    @OPTIONS
    fun getCors(): Response {
        return Response
                .ok()
                .header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE")
                .header("Access-Control-Allow-Headers", "Access-Control-Allow-Origin, Content-Type")
                .header("Access-Control-Max-Age", 86400)
                .type("text/plain")
                .build()
    }

    @Activate
    fun activate() {
        println("Repository resource activated " + this)
    }

    @Deactivate
    fun deactivate() {
        println("Repository resource deactivated " + this)
    }

    @Reference(
            name = "repo",
            service = Repository::class,
            policy = ReferencePolicy.DYNAMIC
    )
    fun bindRepo(repo: Repository) {
        println("Bind repository resource " + this)
        println("Setting reference to repository " + repo)
        this.repo = repo
    }

    fun unbindRepo(repo: Repository) {
        println("Unbind repository resource " + this)
        this.repo = repo
    }

}