import configparser
import os

class iConfig:
    def __init__(self):
        self.path = 'unit_settings'

    def createConfig(self):
        config = configparser.ConfigParser()
        config.add_section('ServerAddress')
        config.set('ServerAddress', 'IP', '')
        config.set('ServerAddress', 'PORT', '')

        with open(self.path, "w") as config_file:
            config.write(config_file)

    def getServerAddress(self, param):
        if not os.path.exists(self.path):
            self.createConfig()
        else:
            config = configparser.ConfigParser()
            config.read(self.path)

        # change config unut values
        ip = config.get('ServerAddress', "IP")
        port = config.get('ServerAddress', "PORT")

        if param is 'IP':
            return ip
        elif param is 'PORT':
            return port
        else:
            return ip, port

    def setServerAddress(self, ip, port):
        if not os.path.exists(self.path):
            self.createConfig()
        else:
            config = configparser.ConfigParser()
            config.read(self.path)

        # change config unut values
        config.set('ServerAddress', "IP", ip)
        config.set('ServerAddress', "PORT", port)
        # config.set("TOKEN", 'token')

        # write config file
        with open(self.path, "w") as config_file:
            config.write(config_file)

    def updateConfig(self, id):

        if not os.path.exists(self.path):
            self.createConfig(self.path)

        config = configparser.ConfigParser()
        config.read(self.path)

        valueToChange = int(config.get("Units", id))
        print('valueToChange, ', valueToChange)

        if valueToChange == 15:
            valueToChange = 0
        else:
            valueToChange += 1

        # change config unut values
        config.set("Units", id, str(valueToChange))

        # Вносим изменения в конфиг. файл.
        with open(self.path, "w") as config_file:
            config.write(config_file)

        return str(valueToChange)