package org.hso.texturesyncclient.controller

import java.io.*
import java.util.Properties


class SettingsController {

    companion object {

        private lateinit var serverAddress: String

        private lateinit var props: Properties

        private val userHome = System.getProperty("user.home")
        private val osName = System.getProperty("os.name")

        private lateinit var dirPath: String //path to settings file
        private lateinit var settingsFile: File //settings file

        private const val defaultAddressValue: String = " "

        fun init() {
            props = Properties()

            dirPath = if (osName.contains("Windows")) {
                "$userHome/Documents/TextureSync"
            } else {
                "$userHome/.TextureSync"
            }

            settingsFile = File("$dirPath/config.xml") //open Settings file

            if (!settingsFile.exists()) {
                println("settings not found! Will create new one")
                File(dirPath).mkdir()
                settingsFile.createNewFile()
                serverAddress = defaultAddressValue //load default value
                saveSettings()
            } else {
                println("settings found")
                loadSettings()
            }
        }

        fun serverAddressIsSet(): Boolean {
            if (serverAddress == defaultAddressValue) {
                return false
            }
            return true
        }

        private fun loadSettings() {
            val inputStream: InputStream
            inputStream = FileInputStream(settingsFile)
            props.loadFromXML(inputStream)
            serverAddress = props.getProperty("serverAddress")
            inputStream.close()
        }

        private fun saveSettings() {
            val outputStream: OutputStream
            props.setProperty("serverAddress", serverAddress)
            outputStream = FileOutputStream(settingsFile)
            props.storeToXML(outputStream, "TextureSync settings")
            outputStream.close()
            println("settings saved")
        }

        fun getServerAddress(): String {
            return serverAddress
        }

        fun setServerAddress(serverAddress: String) {
            this.serverAddress = serverAddress
            saveSettings()
        }
    }
}