package kr.lunaticbum.back.lun.controllers

import com.google.gson.Gson
import jakarta.servlet.http.HttpServletResponse
import kr.lunaticbum.back.lun.model.PostManager
import kr.lunaticbum.back.lun.model.ResultMV
import kr.lunaticbum.back.lun.utils.LogService
import net.coobird.thumbnailator.Thumbnails
import org.commonmark.node.Node
import org.commonmark.parser.Parser
import org.commonmark.renderer.html.HtmlRenderer
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.data.domain.Pageable
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.io.File
import java.io.IOException
import java.net.URLDecoder

@RestController
@RequestMapping()
class Home {

    @Autowired
    lateinit var logService: LogService

    @Autowired
    private lateinit var postManager: PostManager

    @GetMapping("/","/home.bs")
    fun home() : ResultMV {
        val vm = ResultMV("content/home")
        try {
            vm.modelMap.put("Posts", postManager.find4().apply {
                this.forEach {
                    it.title = URLDecoder.decode(it.title)
                    it.content = URLDecoder.decode(it.content)
                    val parser: Parser = Parser.builder().build()
                    val document: Node = parser.parse(it.content)
                    val renderer = HtmlRenderer.builder().build()
                    Jsoup.parse(renderer.render(document))?.let { doc ->
                        val firstImg: Element? = doc.select("img")?.first()
                        val imgSrc: String = firstImg?.attr("src") ?: ""
                        it.image = imgSrc
                        it.thumb = imgSrc.replace(imgSrc.split("/").last(), imgSrc.split("/").last().replace(".","_thumbnail."))
                        generateThumbnail(imgSrc.split("/").last(), 200)
                        it.html = doc.text()
                    }
                    it.title = if ((it.title?.length ?: 0) >= 1) it.title else ""
                }
            }.chunked(2))
        }catch (ex: Exception){ex.printStackTrace()}
        vm.modelMap.put("path","/blog/viewer/")
        return vm
    }

    @Value("\${image.upload.path}")
    private val uploadPath: String? = null

    @Value("\${resource.handler}")
    private val resourceHandler: String? = null

    fun generateThumbnail(originalPath: String, targetWidth: Int) {
        try {
            val originalFile = File("$uploadPath${File.separator}$originalPath")
            println("origin ${originalPath}")
            println("thumb ${originalPath
                .replace(".", "_thumbnail.")}")
            // 썸네일 경로 생성 (예: /upload/uuid.jpg → /upload/uuid_thumbnail.jpg)
            val thumbnailPath = originalPath
                .replace(".", "_thumbnail.")


            val thumbnailFile = File("$uploadPath${File.separator}$thumbnailPath")
            // 썸네일 이미 존재하면 종료
            if (thumbnailFile.exists()) {
                println("썸네일 이미 존재: $thumbnailPath")
                return
            }


            // 원본 파일 존재 확인
            if (!originalFile.exists()) {
                println("원본 파일 없음: $originalPath")
                return
            }

            // 썸네일 생성 (가로 기준 비율 유지)
            Thumbnails.of(originalFile)
                .width(targetWidth)
                .keepAspectRatio(true)
                .toFile(thumbnailFile)

            println("썸네일 생성 완료: $thumbnailFile")
        } catch (e: IOException) {
            println("썸네일 생성 실패: ${e.message}")
        }
    }


    @GetMapping("/h2")
    fun home2() : ResultMV {
        val vm = ResultMV("content/index_ex")
        vm.modelMap.put("Posts", postManager.find20(Pageable.ofSize(20)).apply {
            this.forEach {
                it.title = URLDecoder.decode(it.title)
                it.content = URLDecoder.decode(it.content)
                logService.log(Gson().toJson(it))
            }
        })
        return vm
    }

    @GetMapping("/left-sidebar")
    fun lside() : ResultMV {
        val vm = ResultMV("content/left-sidebar")
        vm.modelMap.put("Posts", postManager.find20(Pageable.ofSize(20)).apply {
            this.forEach {
                it.title = URLDecoder.decode(it.title)
                it.content = URLDecoder.decode(it.content)
                logService.log(Gson().toJson(it))
            }
        })
        return vm
    }
    @GetMapping("/no-sidebar")
    fun nside() : ResultMV {
        val vm = ResultMV("content/no-sidebar")
        vm.modelMap.put("Posts", postManager.find20(Pageable.ofSize(20)).apply {
            this.forEach {
                it.title = URLDecoder.decode(it.title)
                it.content = URLDecoder.decode(it.content)
                logService.log(Gson().toJson(it))
            }
        })
        return vm
    }

    @GetMapping("/right-sidebar")
    fun rside() : ResultMV {
        val vm = ResultMV("content/right-sidebar")
        vm.modelMap.put("Posts", postManager.find20(Pageable.ofSize(20)).apply {
            this.forEach {
                it.title = URLDecoder.decode(it.title)
                it.content = URLDecoder.decode(it.content)
                logService.log(Gson().toJson(it))
            }
        })
        return vm
    }

    @GetMapping("/two-sidebar")
    fun bside() : ResultMV {
        val vm = ResultMV("content/two-sidebar")
        vm.modelMap.put("Posts", postManager.find20(Pageable.ofSize(20)).apply {
            this.forEach {
                it.title = URLDecoder.decode(it.title)
                it.content = URLDecoder.decode(it.content)
                logService.log(Gson().toJson(it))
            }
        })
        return vm
    }




    @GetMapping("/login")
    fun login(response: HttpServletResponse) {
        response.sendRedirect("/user/login")
    }

    @GetMapping("/licenses")
    fun licenses() : ResultMV {
        val vm = ResultMV("content/licenses")
        return vm
    }

}