import pygame
import codecs
import os
from locals import *

# Some general utility functions here

pygame.font.init()

# The Cosmetica font seemed to be broken... had trouble rendering small text
# with underscores (_) ... it's weird.
smallfont = pygame.font.Font("data/Vera.ttf", 14)
bigfont = pygame.font.Font("data/Vera.ttf", 20)

def get_config_path():
    pathname = ""
    try:
        pathname = os.environ["HOME"] + "/.zombie"
    except:
        try:
            pathname = os.environ["APPDATA"] + "/Zombie"
        except:
            print "Couldn't get environment variable for home directory"
            pathname = "."
    if not os.path.exists(pathname):
        os.mkdir(pathname)
    return pathname

def str_to_bool(text):
    ltext = text.lower().strip()
    if ltext in ("on", "true", "yes"):
        return True
    else:
        return False

def str_to_bool(text):
    ltext = text.lower().strip()
    if ltext in ("on", "true", "yes"):
        return True
    else:
        return False

def load_config():
    filename = get_config_path() + "/config"
    if not os.path.exists(filename):
        return
    f = codecs.open(filename, "r", "utf_8")

    for line in f.readlines():
        parts = line.split("\t")
        if len(parts) < 2:
            continue
        variable,value = parts
        variable = variable.lower()
        if variable == "sound":
            Variables.sound = str_to_bool(value)
        if variable == "psychomode":
            Variables.psychomode = str_to_bool(value)
        elif variable == "music":
            Variables.music = str_to_bool(value)
        elif variable == "name":
            Variables.name = value.strip()[:32]

    f.close()

def save_config():
    filename = get_config_path() + "/config"
    f = codecs.open(filename, "w", "utf_8")

    print >> f, "sound\t%s" % Variables.sound
    print >> f, "psychomode\t%s" % Variables.psychomode
    print >> f, "music\t%s" % Variables.music
    print >> f, "name\t%s" % Variables.name

    f.close()

def load_sound(name):
    return pygame.mixer.Sound("data/" + name + ".ogg")

def load_music(name):
    pygame.mixer.music.load("data/" + name + ".ogg")
