package com.andr3h3nriqu3s.applications

import java.sql.ResultSet
import java.util.Date
import java.util.UUID
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.jdbc.core.RowMapper
import org.springframework.stereotype.Service

data class View(var id: String, var application_id: String, var time: Date) {
    companion object : RowMapper<View> {
        override public fun mapRow(rs: ResultSet, rowNum: Int): View {
            return View(
                    rs.getString("id"),
                    rs.getString("application_id"),
                    rs.getDate("time"),
            )
        }
    }
}

@Service
public class ViewService(val db: JdbcTemplate) {

    public fun listFromApplicationId(id: String): List<View> =
            db.query("select * from views where application_id=?;", arrayOf(id), View).toList()

    public fun getById(id: String): View? {
        val items = db.query("select * from views where id=?;", arrayOf(id), View).toList()
        if (items.size == 0) {
            return null
        }
        return items[0]
    }

    public fun deleteById(id: String): View {
        val view = this.getById(id)
        if (view == null) {
            throw NotFound()
        }

        db.update("delete from views where id=?", id)

        return view
    }

    public fun update(view: View): View {
        db.update(
                "update views set application_id=?, time=? where id=?;",
                view.application_id,
                view.time,
                view.id,
        )

        return view
    }

    public fun create(application_id: String): View {
        val id = UUID.randomUUID().toString()

        var new_view = View(id, application_id, Date())

        db.update(
                "insert into views (id, application_id) values (?, ?)",
                new_view.id,
                new_view.application_id
        )

        return new_view
    }
}
