package org.hso.texturesyncclient.model

import java.lang.IllegalArgumentException
import java.util.*
import java.security.MessageDigest


enum class TextureFormat {
    PNG, JPEG,
}

@Suppress("ArrayInDataClass")
data class Texture(
    val id : UUID,
    val name : String,
    var tags : Array<String>,
    val format : TextureFormat,
    val resolution : Pair<Int, Int>,
    val addedOn : Calendar,
    val textureHash : Sha256
)

@Suppress("ArrayInDataClass")
class Sha256 {

    private val hashBytes : ByteArray

    @Throws(IllegalArgumentException::class)
    constructor(hex : String) {

        if(hex.length != 64) {
            throw IllegalArgumentException("Sha256 has wrong length.")
        }

        try {
            hashBytes = ByteArray(hex.length / 2) { i ->
                hex.substring(i * 2, i * 2 + 2).toInt(16).toByte()
            }
        }catch(n : NumberFormatException) {
            throw IllegalArgumentException("Hash does not only Contain '0-9a-zA-Z'.")
        }
    }

    constructor(data : ByteArray ) {
        val digest = MessageDigest.getInstance("SHA-256")
        hashBytes = digest.digest(data)
    }

    override fun toString(): String {
        val s = StringBuilder(64)
        for (byte in hashBytes) {
            s.append(String.format("%02X", byte))
        }
        return s.toString()
    }

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as Sha256

        if (!hashBytes.contentEquals(other.hashBytes)) return false

        return true
    }

    override fun hashCode(): Int {
        return hashBytes.contentHashCode()
    }
}