import settinglib
from settinglib import Setting_base

import es
import os
import time
import playerlib
import popuplib

import psyco
psyco.full()

## Setting_setting class is the setting base class
class Setting_toggle(Setting_base):
    def __init__(self, pSettingid, pDescription, pFilename, pFiletype):
        #initialization of setting
        self.name = pSettingid          #setting name for backwards compatibility
        self.descr = pDescription       #description
        self.filename = pFilename
        self.filetype = pFiletype
        Setting_base.__init__(self, 'toggle')
    def send(self, pUsers, prio=False, locked=False):
        try:
            # try if pUsers is just a single userid
            userid = int(pUsers)
            pUsers = [userid]
        except TypeError:
            pass
        if locked:
            optionstate = 0
        else:
            optionstate = 1
        for userid in pUsers:
            player = playerlib.getPlayer(userid)
            if player:
                steamid = playerlib.uniqueid(userid, True)
                helpline = self.languages("setting "+self.keyvalues["config"]["type"]+" help", (), player.get("lang"))
                oldpage = popuplib.find("_setting_"+str(self.name)+"_user"+str(userid))
                if oldpage:
                    oldpage.delete()
                self.popup[userid] = popuplib.easymenu("_setting_"+str(self.name)+"_user"+str(userid), "_setting_choice", settinglib._submit)
                self.popup[userid].settingid = self.name
                self.popup[userid].c_titleformat = str(self.keyvalues["config"]["descr"]) + (" "*(30-len(str(self.keyvalues["config"]["descr"])))) + " (%p/%t)\n" + helpline
                if not steamid in self.keyvalues["users"]:
                    self.initUser(userid)
                for option in self.keyvalues["options"]:
                    index = int(str(option))
                    display = self.keyvalues["options"][str(option)]["display"]
                    if self.keyvalues["users"][steamid]["data"][str(option)]["state"] == True:
                        active = self.languages("setting toggle on", (), player.get("lang"))
                        self.popup[userid].addoption(index, display + " ("+active+")", optionstate)
                    else:
                        active = self.languages("setting toggle off", (), player.get("lang"))
                        self.popup[userid].addoption(index, display + " ("+active+")", optionstate)
                if self.backmenuvar:
                    self.popup[userid].submenu(10, self.backmenuvar)
                self.popup[userid].send(userid, prio)
    def sendglobal(self, pUsers, prio=False, locked=False):
        try:
            # try if pUsers is just a single userid
            userid = int(pUsers)
            pUsers = [userid]
        except TypeError:
            pass
        if locked:
            optionstate = 0
        else:
            optionstate = 1
        for userid in pUsers:
            player = playerlib.getPlayer(userid)
            if player:
                helpline = self.languages("setting "+self.keyvalues["config"]["type"]+" help", (), player.get("lang"))
                oldpage = popuplib.find("_setting_"+str(self.name)+"_user"+str(userid)+"_global")
                if oldpage:
                    oldpage.delete()
                self.popup["global"] = popuplib.easymenu("_setting_"+str(self.name)+"_user"+str(userid)+"_global", "_setting_choice", settinglib._submitGlobal)
                self.popup["global"].settingid = self.name
                self.popup["global"].c_titleformat = str(self.keyvalues["config"]["descr"]) + (" "*(30-len(str(self.keyvalues["config"]["descr"])))) + " (%p/%t)\n" + helpline
                for option in self.keyvalues["options"]:
                    index = int(str(option))
                    display = self.keyvalues["options"][str(option)]["display"]
                    if self.keyvalues["options"][str(option)]["globstate"] == True:
                        active = self.languages("setting toggle on", (), player.get("lang"))
                        self.popup["global"].addoption(index, display + " ("+active+")", optionstate)
                    else:
                        active = self.languages("setting toggle off", (), player.get("lang"))
                        self.popup["global"].addoption(index, display + " ("+active+")", optionstate)
                if self.backmenuvar:
                    self.popup["global"].submenu(10, self.backmenuvar)
                self.popup["global"].send(userid, prio)
    def menuUserSubmit(self, userid, value):
        if es.exists('userid',userid):
            self.toggle(int(value), userid)
            if self.keyvalues["config"]["sound"]:
                es.playsound(userid, self.keyvalues["config"]["sound"], 1.0)
            if self.keyvalues["config"]["resend"] == True:
                self.send(userid, True)
    def menuUserGlobalSubmit(self, userid, value):
        if es.exists('userid',userid):
            self.toggle(int(value))
            if self.keyvalues["config"]["sound"]:
                es.playsound(userid, self.keyvalues["config"]["sound"], 1.0)
            if self.keyvalues["config"]["resend"] == True:
                self.sendglobal(userid, True)
    def setoption(self, option, text, state=None):    #edit/add an option
        option = str(self.isValidOption(option))
        if option:
            for thisoption in self.keyvalues["options"]:
                if int(str(thisoption)) == int(option):
                    self.keyvalues["options"][str(thisoption)]["display"] = text
                    if state != None and (state == True or state == False):
                        self.keyvalues["options"][str(thisoption)]["state"] = state
            self.save()
        else:
            es.dbgmsg(0,"Settinglib: Cannot modify option #"+str(option)+"("+text+") in "+self.name)
    def addoption(self, key, text, state=None):            #add an option to the end of the list
        option = str(len(self.keyvalues["options"].keys())+1)
        for thisoption in self.keyvalues["options"]:
            if self.keyvalues["options"][str(thisoption)]["keyname"] == key:
                option = str(thisoption)
        self.keyvalues["options"][option] = self.createKey(option)
        self.keyvalues["options"][option]["keyname"] = key
        self.keyvalues["options"][option]["display"] = text
        if state != None and (state == True or state == False):
            self.keyvalues["options"][option]["state"] = state
            self.keyvalues["options"][option]["globstate"] = state
        else:
            self.keyvalues["options"][option]["state"] = False
            self.keyvalues["options"][option]["globstate"] = False
        self.save()
    def deloption(self, option):          #delete an option
        arg = option
        option = self.isValidOption(option)
        if option:
            options = len(self.keyvalues["options"].keys())
            for thisoption in range(int(option),options):
                if str(thisoption+1) in self.keyvalues["options"]:
                    self.keyvalues["options"][str(thisoption)] = self.keyvalues["options"][thisoption+1]
            del self.keyvalues["options"][str(options)]
            for steamid in self.keyvalues["users"]:
                for thisoption in range(int(option),options):
                    if str(thisoption+1) in self.keyvalues["users"][str(steamid)]["data"]:
                        self.keyvalues["users"][str(steamid)]["data"][str(thisoption)] = self.keyvalues["users"][str(steamid)]["data"][str(thisoption+1)]
                if str(options) in self.keyvalues["users"][str(steamid)]["data"]:
                    del self.keyvalues["users"][str(steamid)]["data"][str(options)]
            self.save()
        else:
            raise IndexError("Settinglib: Cannot delete option %s, it does not exists"%arg)
    def setdefault(self, option, state=None, overwrite=None):
        arg = option
        option = str(self.isValidOption(option))
        if option:
            if state:
                self.keyvalues["options"][str(option)]["state"] = 1
            else:
                self.keyvalues["options"][str(option)]["state"] = 0
            if overwrite:
                for steamid in self.keyvalues["users"]:
                    if state:
                        self.keyvalues["users"][str(steamid)]["data"][option]["state"] = 1
                    else:
                        self.keyvalues["users"][str(steamid)]["data"][option]["state"] = 0
        else:
            raise IndexError("Settinglib: Cannot set option %s as default, it does not exists"%arg)
    def set(self, option, state=None, userid=None):
        arg = option
        option = str(self.isValidOption(option))
        if option:
            if userid:
                steamid = playerlib.uniqueid(userid, True)
                if steamid:
                    if not steamid in self.keyvalues["users"]:
                        self.initUser(int(userid))
                    if state:
                        self.keyvalues["users"][str(steamid)]["data"][str(option)]["state"] = 1
                    else:
                        self.keyvalues["users"][str(steamid)]["data"][str(option)]["state"] = 0
                else:
                    raise IndexError("Settinglib: Cannot find userid %s"%userid)
            else:
                if state:
                    self.keyvalues["options"][str(option)]["globstate"] = 1
                else:
                    self.keyvalues["options"][str(option)]["globstate"] = 0
        else:
            raise IndexError("Settinglib: Cannot set option #%s, it does not exists"%arg)
    def get(self, option=None, userid=None):
        arg = option
        option = str(self.isValidOption(option))
        if option:
            if userid:
                steamid = playerlib.uniqueid(userid, True)
                if steamid:
                    if not steamid in self.keyvalues["users"]:
                        self.initUser(int(userid))
                    try:
                        result = bool(int(str(self.keyvalues["users"][str(steamid)]["data"][str(option)]["state"])))
                    except KeyError:
                        result = bool(int(str(self.keyvalues["options"][str(option)]["state"])))
                    return result
                else:
                    raise IndexError("Settinglib: Cannot find userid %s"%userid)
            else:
                return bool(int(str(self.keyvalues["options"][str(option)]["globstate"])))
        else:
            raise IndexError("Settinglib: Cannot get option #%s, it does not exists"%arg)
    def toggle(self, option, userid=None):
        arg = option
        option = self.isValidOption(option)
        if option:
            state = self.get(option, userid)
            if state:
                self.set(option, False, userid)
            else:
                self.set(option, True, userid)
        else:
            raise IndexError("Settinglib: Cannot toggle option #%s, it does not exists"%arg)
