package de.kif.backend

import de.kif.backend.database.Connection
import de.kif.backend.repository.UserRepository
import de.kif.common.model.Permission
import de.kif.common.model.User
import io.ktor.application.Application
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import kotlinx.coroutines.runBlocking
import java.nio.file.Files

object Main {
    @Suppress("UnusedMainParameter")
    @JvmStatic
    fun main(args: Array<String>) {
        Resources.init()

        Connection.init()

        // twitter()

        runBlocking {
            if (UserRepository.all().isEmpty()) {

                println("Please create a root user")

                var username: String? = null
                while (username == null) {
                    print("Username: ")
                    username = readLine()
                }

                var password: String? = null
                while (password == null) {
                    print("Password: ")
                    password = System.console()?.readPassword()?.toString() ?: readLine()
                }

                println("Create root user '$username' with pw '${"*".repeat(password.length)}'")

                UserRepository.create(
                    User(
                        null,
                        username,
                        hashPassword(password),
                        setOf(Permission.ADMIN)
                    )
                )
            }
        }

        embeddedServer(
            factory = Netty,
            port = Configuration.Server.port,
            host = Configuration.Server.host,
            module = Application::main
        ).start(wait = true)
    }
}
