#v1.0.1

import win32gui, win32con, sys, os
import dataIO

sp_json = "setpoints.json"
sens = 0

def set_spi(spi, value):
    value = int(value)
    try:
        cset=getattr(win32con,spi)
        set = win32gui.SystemParametersInfo(cset, Param=value, WinIni=1)
        return True
    except WindowsError:
        return False
        
def get_spi(spi):
    try:
        cget=getattr(win32con,spi)
        value=win32gui.SystemParametersInfo(cget)
        return value
    except WindowsError:
        return None

def checkValue(sens):
    if sens.isdigit():
        if int(sens) in range(1,21):            
            return True
        else:
            print ('setpoint out of range, 1...20')
            return False
    else:
        print('Numbers only, 1...20')
        return False

def writeSense(sens):
    if set_spi('SPI_SETMOUSESPEED', str(sens)) == True: #MouseSensitivity = 1/20
        print ('\nAdjusting sensitivity to {} went successful.'.format(sens))
    else:
        print ('Something went wrong while writing.')  

if __name__ == '__main__':
    #Appdata/Roaming
    global ROAMING
    setpoints = {}
    APP_DIRNAME = 'SwitchMouseSensitivity'
    if not os.path.exists(os.path.join(os.environ['APPDATA'],APP_DIRNAME)):
        try:
            os.mkdir(os.path.join(os.environ['APPDATA'],APP_DIRNAME))
            ROAMING = os.path.join(os.environ['APPDATA'],APP_DIRNAME)
        except:
            print('Error creating settings folder')       
    ROAMING = os.environ['APPDATA']+'\\'+APP_DIRNAME+'\\' 
    dataIO.loadAndCheckSettings(ROAMING, True)
    setpoints = dataIO.fileIO(ROAMING+sp_json, "load")
    
    #Get current sensitivity and save to json
    setpoints["curReg"] = setpoints["curReg"] = get_spi('SPI_GETMOUSESPEED')
    dataIO.fileIO(ROAMING+sp_json, "save", setpoints)
    print ('Current mouse sensitivity : '+str(setpoints["curReg"]))
    
    #Check for run parameter
    if len(sys.argv) > 1: #arguments is given
        sens = sys.argv[1]
        if checkValue(sens) == True:
            print ('Changing the sensitivity by run parameter to: '+sens)
            writeSense(sens)
            os.system('pause')
            exit(1)

    #Read previous setpoint
    if setpoints["lastSp"] == "sp2":
        sens = setpoints["sp1"]
    elif setpoints["lastSp"] == "sp1":
        sens = setpoints["sp2"] 

    #Confirm switch setpoint
    if sens is not 0:
        print ('The setpoint before the previous one was {}, apply this value? y/n: '.format(sens), end='')
        confirmInput = input()
    else:
        confirmInput = 'n'
 
    if confirmInput == 'y' or confirmInput == '': 
        if setpoints["lastSp"] == "sp2":
            sens = setpoints["sp1"] 
            setpoints["lastSp"] = setpoints["lastSp"] ='sp1'
            dataIO.fileIO(ROAMING+sp_json, "save", setpoints)
        elif setpoints["lastSp"] == "sp1":
            sens = setpoints["sp2"] 
            setpoints["lastSp"] = setpoints["lastSp"] ='sp2'
            dataIO.fileIO(ROAMING+sp_json, "save", setpoints)
    elif confirmInput == 'n':
        sens = input("Enter the preferred sensitivity : ") 
        if checkValue(sens) == True:            
            if setpoints["lastSp"] == "sp2" and setpoints["sp2"] is not '0':
                setpoints["sp1"] = setpoints["sp1"] = sens
                sens = setpoints["sp1"] 
                setpoints["lastSp"] = setpoints["lastSp"] ='sp1'
                dataIO.fileIO(ROAMING+sp_json, "save", setpoints)
                print('Setpoint {} is now registered'.format(sens))                
            elif setpoints["lastSp"] == "sp1" and setpoints["sp1"] is not '0':
                setpoints["sp2"] = setpoints["sp2"] = sens
                sens = setpoints["sp2"] 
                setpoints["lastSp"] = setpoints["lastSp"] ='sp2'
                dataIO.fileIO(ROAMING+sp_json, "save", setpoints)
                print('Setpoint {} is now registered'.format(sens))  
            else:#should be displayed only the first two sp changes
                print('Setpoint {} is now registered'.format(sens))               
    writeSense(sens)
    dataIO.fileIO(ROAMING+sp_json, "save", setpoints)

os.system('pause')
