package uk.co.rossbinden.transferencevoid.screen

import com.badlogic.gdx.Gdx
import com.badlogic.gdx.InputAdapter
import com.badlogic.gdx.ScreenAdapter
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.maps.tiled.TiledMap
import uk.co.rossbinden.transferencevoid.TransferenceVoid
import uk.co.rossbinden.transferencevoid.TransferenceVoid.assetManager
import java.net.Inet4Address
import java.net.NetworkInterface
import java.util.*


object StartScreen: ScreenAdapter() {

    val spriteBatch = SpriteBatch()
    var mapInit = false

    val inputProcessor = object: InputAdapter() {

        override fun keyDown(keycode: Int): Boolean {
            TransferenceVoid.screen = MainScreen
            return true
        }

    }

    init {
        assetManager.load("fonts/envy_code_r_32.fnt", BitmapFont::class.java)
        assetManager.load("textures/textures.atlas", TextureAtlas::class.java)
        assetManager.load("maps/one.tmx", TiledMap::class.java)
    }

    override fun show() {
        Gdx.input.inputProcessor = inputProcessor
    }

    override fun hide() {
        Gdx.input.inputProcessor = null
    }

    override fun render(delta: Float) {
        if (assetManager.isLoaded("fonts/envy_code_r_32.fnt") && assetManager.isLoaded("textures/textures.atlas") && assetManager.isLoaded("maps/one.tmx")) {
            if (!mapInit) {
                MainScreen.loadMap()
                mapInit = true
            }
            Gdx.gl.glClearColor(0f, 0f, 0f, 1f)
            val font = assetManager.get("fonts/envy_code_r_32.fnt", BitmapFont::class.java)
            spriteBatch.begin()

            font.draw(spriteBatch, "Players on the left: Download the data from the terminals and transmit", 32f, 224f)
            font.draw(spriteBatch, "it to the players on the right", 32f, 192f)
            font.draw(spriteBatch, "Players on the right: Receive the transmissions from the players on", 32f, 160f)
            font.draw(spriteBatch, "the left and upload it to the core", 32f, 128f)
            val ip = Collections.list(NetworkInterface.getNetworkInterfaces()).stream()
                    .flatMap({ i -> Collections.list(i.inetAddresses).stream() })
                    .filter({ ip -> ip is Inet4Address && ip.isSiteLocalAddress() })
                    .findFirst()
                    .orElseGet(null)
                    .toString()
                    .substring(1)
            font.draw(spriteBatch, "Connect your phone to $ip:30507/controller", 32f, 96f)
            font.draw(spriteBatch, "Press any key to start.", 32f, 64f)
            spriteBatch.end()
        } else {
            assetManager.update()
        }
    }

    override fun dispose() {
        spriteBatch.dispose()
    }

}