# -*- coding: utf-8 -*-
"""
Created on Wed Feb  8 12:47:21 2017

@author: Gazatus
"""

import os 
import win32api
import sys
import ctypes
import requests

#Initialisation Logs
system=sys.getwindowsversion()[0],sys.getwindowsversion()[2]
log="########################### START LOG ###########################\nPatch1366.py\n\n"
log+="System Version :\nWindows "+str(system[0])+" ( Build : "+str(system[1])+" )\n"
                                      
#Messagebox
MB_OK = 0
MB_OKCANCEL = 1
MB_YESNOCANCEL = 3
MB_YESNO = 4

IDOK = 0
IDCANCEL = 2
IDABORT = 3
IDYES = 6
IDNO = 7

#var
ok = 1 #"while" var
mode=0 #first video mode
endloop=0
succes=0 #while this var = 0 -> there is no suitable video mode 

#Avoid DPI scaling
if system[0]>=6:
    ctypes.windll.user32.SetProcessDPIAware()
while ok == 1:
    try:
        smode = win32api.EnumDisplaySettings(None, mode) #first display mode infos
        log+="\nEnumDisplaySettings :\n"+str(mode)+"\t"+str(smode.PelsWidth)+"\t"+str(smode.PelsHeight)+"\n"
        if smode.PelsWidth==1366 and smode.PelsHeight==768: #have we found a suitable video mode ? -> need to found the last video mode suitable
            succes=1
        if smode.PelsWidth>1366 and smode.PelsHeight>768 and succes==1:
            ok = 0
        if smode.PelsWidth>1366 and smode.PelsHeight>768 and succes==0: #are we out of bounds and no video mode founded ?
            log+="\n\n###############################################\nFail : Can't find 1366x768 video mode.\n############################################\n"
            result=ctypes.windll.user32.MessageBoxW(0, "Please report this issue, you can see the error_log.xls on desktop or would you like to send the report on the dev's server ?", "Patch Error", MB_YESNO)
            ok=0
            if result==IDNO:
                name=os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop')+"\error_log"
                filename = "%s.xls" % name
                f=open(filename , 'w')
                f.write(log)
                f.close()
            elif result==IDYES:
                r = requests.post('https://gaza-tools.000webhostapp.com/koh/koh_telemetry_error.php', data = {'report':log})  
        if ok==1:
            mode += 1 #increment mode
    except:
        ok=0
        log+="\n\nVideoMode :\n"+str(mode)+"\t"+str(smode.PelsWidth)+"\t"+str(smode.PelsHeight)+"\n\n"
        mode=2*mode-1 #cheating on KoH recognition
        endloop=1
if succes==1: #if we have a suitable video mode let's do some chnage in Koh.in2
    if endloop==0:
        log+="\n\nVideoMode :\n"+str(mode)+"\t"+str(smode.PelsWidth)+"\t"+str(smode.PelsHeight)+"\n\n"
        mode=2*mode-1 #cheating on KoH recognition
    name=os.getenv('APPDATA')+"\Black Sea Studios\Knights of Honor\KoH"
    log+="KoH.in2 path :\n"+str(name)+".in2" #cursor on the correct file
    filename = "%s.in2" % name
    try:
        f = open(filename , 'r')
        lines=f.read()
        log+="\n\nKoH.in2 content :\n"+str(lines)
        f.close()
    except IOError:
        lines="""[app]
user = 1
[video]
fullscreen = 1
mode = 71
width = 1366
height = 768
freq = 60
[sound]
disable = 0
notifsizems = 400
notifnumber = 5
forceswbuffers = 0
forcehwbuffers = 0
[network]
sptick = 40
mptick = 250
"""    
    log+="\n\nKoH.in2 sdandard content :\n"+str(lines)
    f=open(filename , 'w')
    for i in range(len(lines)): #first copy everything before mode
        if lines[i:i+4]=="mode":
            j=i+4
            while lines[j]!="w":
                 j+=1
            linesaux=lines[:i] #add our mode=xxx
            linesaux+="mode = "
            linesaux+=str(mode)
            break
    for i in range(len(lines)): #finally add the rest of the file except old mode=xxx
        if lines[i:i+5]=="width":
            linesaux+=lines[i-1:]
            succes=2
            break
    if succes!=2:
        log+="\n\n###############################################\nFail : KoH.in2 can't be edited.\n############################################\n"
        result=ctypes.windll.user32.MessageBoxW(0, "Please report this issue, you can see the error_log.xls on desktop or would you like to send the report on the dev's server ?", "Patch Error", MB_YESNO)
        if result==IDNO:
            name=os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop')+"\error_log"
            filename = "%s.xls" % name
            f=open(filename , 'w')
            f.write(log)
            f.close()
        elif result==IDYES:
            r = requests.post('https://gaza-tools.000webhostapp.com/koh/koh_telemetry_error.php', data = {'report':log})
    else:
        f.write(linesaux)
        log+="\n\nKoH.in2 new content :\n"+str(linesaux)+"\n\n########################### END OF THE LOG ###########################"
        f.close()
        result=ctypes.windll.user32.MessageBoxW(0, "Game have been patched ! Would you like to send a report on the dev's server ?", "Patch Success", MB_YESNO)
        if result==IDYES:
            r = requests.post('https://gaza-tools.000webhostapp.com/koh/koh_telemetry_success.php', data = {'report':log})
    result=ctypes.windll.user32.MessageBoxW(0, "Please don't foget to untick the last 2 graphic settings in-game. Okay :) ?", "Patch Warning", MB_YESNO)
    ok=1
    while result==IDNO:
        if ok>142:
            result=ctypes.windll.user32.MessageBoxW(0, "Ok, send me a PM on ModDB (@Gazatus) with the keyword 'Penis'. I'll give you something x) Ok ?", "Patch Winning", MB_YESNO)
            easter_egg= requests.post('https://gaza-tools.000webhostapp.com/koh/koh_counter_easter.php', data = {})
            break
        else:
            result=ctypes.windll.user32.MessageBoxW(0, "Please don't foget to untick the last 2 graphic settings in-game. Do you have understand :) ? (x"+str(ok)+")", "Patch Warning", MB_YESNO)
            ok+=1
final = requests.post('https://gaza-tools.000webhostapp.com/koh/koh_counter.php', data = {})