package com.nisemoe.nise.controller

import com.nisemoe.nise.*
import com.nisemoe.nise.database.ScoreService
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RestController

@RestController
class ScoreController(
    private val scoreService: ScoreService
) {

    @GetMapping("score/{replayId}/replay")
    fun getReplay(@PathVariable replayId: Long): ResponseEntity<ReplayViewerData> {
        val replay = this.scoreService.getReplayViewerData(replayId)
            ?: return ResponseEntity.notFound().build()

        return ResponseEntity.ok(replay)
    }

    @GetMapping("score/{replayId}")
    fun getScoreDetails(@PathVariable replayId: Long): ResponseEntity<ReplayData> {
        val replayData = this.scoreService.getReplayData(replayId)
            ?: return ResponseEntity.notFound().build()

        return ResponseEntity.ok(replayData)
    }

    @GetMapping("pair/{replay1Id}/{replay2Id}/replay")
    fun getPairReplays(@PathVariable replay1Id: Long, @PathVariable replay2Id: Long): ResponseEntity<ReplayPairViewerData> {
        val replayPairViewerData = this.scoreService.getReplayPairViewerData(replay1Id, replay2Id)
            ?: return ResponseEntity.notFound().build()

        return ResponseEntity.ok(replayPairViewerData)
    }

    @GetMapping("pair/{replay1Id}/{replay2Id}")
    fun getPairDetails(@PathVariable replay1Id: Long, @PathVariable replay2Id: Long): ResponseEntity<ReplayPair> {
        val replay1Data = this.scoreService.getReplayData(replay1Id)
            ?: return ResponseEntity.notFound().build()

        val replay2Data = this.scoreService.getReplayData(replay2Id)
            ?: return ResponseEntity.notFound().build()

        val replayPairStatistics = this.scoreService.getPairInfo(replay1Id, replay2Id)
            ?: return ResponseEntity.notFound().build()

        // Sort replays by date (the first replay will always be the oldest)
        val replays = listOf(replay1Data, replay2Data)
            .sortedBy { Format.parseStringToDate(it.date) }

        val replayPair = ReplayPair(replays, replayPairStatistics)

        return ResponseEntity.ok(replayPair)
    }

}