#!/usr/bin/env python

import MySQLdb
import os
import time
import sys

pid=os.getpid()
myfile = open('pid','w')
myfile.write(str(pid))
myfile.close()

db = MySQLdb.connect(host="localhost",user="D8912HDKSD",passwd="AS890DJ1P2DU89Q",db="metin")
cursor = db.cursor()

rootdir = sys.argv[1]
zoneid = '1'
while True:
    for gamen in range(1,10):
        allpath = rootdir+'/game'+str(gamen)+'/log'
        if not os.path.isdir(allpath):
            break;
        list = os.listdir(allpath)
        for logpathi in range(0,len(list)):
            path = os.path.join(allpath,list[logpathi])
            logfilelist = os.listdir(path)
            for logfilej in range(0,len(logfilelist)):
                logpath = os.path.join(path,logfilelist[logfilej])
                try:
                    with open(logpath, 'r') as file:
                        for line in file:
                            strline = line.strip()
                            if len(strline)<=0:
                                continue
                            sql = 'INSERT INTO game_log (time , content,zone_id ) VALUES (%s,%s,%s)'
                            logtime = str(list[logpathi][0:4]+'-'+list[logpathi][4:6]+'-'+list[logpathi][6:8]+' '+logfilelist[logfilej][0:2]+':00:00')
                            n = cursor.execute(sql,(logtime,strline,zoneid))
                            #print('INSERT INTO game_log (time , content,zone_id ) VALUES (%s,%s,%s)'%(logtime,strline,zoneid))
                        db.commit()
                        os.remove(logpath)
                        print('%s:delete logfile %s'%(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),logpath))
                except Exception as e:
                    db.rollback()
                    print('%s:%s' % (e,logpath))
                finally:
                    file.close()
    time.sleep(60)
db.close()
