#encoding=utf-8
'''
Created on Nov 26, 2015

@author: lowitty
'''
from logging.handlers import RotatingFileHandler
import logging
from com.ericsson.xn.tools.PyProperties import Properties
import os, time, datetime
from datetime import timedelta
from com.ericsson.xn.tools import CommonFunc
rootpath = os.path.dirname(os.path.abspath(__file__))
logpath = rootpath + os.path.sep + 'logs'
if not os.path.isdir(logpath):
    os.makedirs(logpath)
logfile = logpath + os.path.sep + 'bigfile.log'
logformatter = logging.Formatter('%(asctime)s [%(levelname)s] %(module)s %(funcName)s(%(lineno)d) %(message)s')
loghandler = RotatingFileHandler(logfile, mode='a', maxBytes=10*1024*1024, backupCount=10, encoding='utf-8', delay=0)
loghandler.setFormatter(logformatter)
loghandler.setLevel(10)

log0 = logging.getLogger("BigFile")
log0.setLevel(10)
log0.addHandler(loghandler)
consolehandler = logging.StreamHandler()
consolehandler.setFormatter(logformatter)
consolehandler.setLevel(10)
log0.addHandler(consolehandler)

if __name__ == '__main__':
    #exportPath = '/xcom/alarm/bigfle.txt'
    props = Properties(os.path.normpath(rootpath + os.path.sep + 'conf' + os.path.sep + 'bigfile.conf'))
    counter = int(props.getProperty('counter'))
    limit = int(props.getProperty('limit'))
    li = []
    li.append('|.1.3.6.1.4.1.193.176.50.2.5|1|07:df:0a:07:0e:14:01:00:2b:08:00|Failed to establish X2 connection|3|licId01|Cannot connect to X2 remote address. remote ip [192.168.20.10] port [7790]. errno [67] error description [Address already in use]')
    li.append('|.1.3.6.1.4.1.193.176.50.2.5|2|07:df:0a:07:0e:14:01:00:2b:08:00|Failed to establish X2 connection|3|licId01|Cannot connect to X2 remote address. remote ip [192.168.20.10] port [7790]. errno [67] error description [Address already in use]')
    li.append('|.1.3.6.1.4.1.193.176.50.2.5|3|07:df:0a:07:0e:14:01:00:2b:08:00|Failed to establish X2 connection|3|licId01|Cannot connect to X2 remote address. remote ip [192.168.20.10] port [7790]. errno [67] error description [Address already in use]')
    li.append('|.1.3.6.1.4.1.193.176.50.2.5|4|07:df:0a:07:0e:14:01:00:2b:08:00|Failed to establish X2 connection|3|licId01|Cannot connect to X2 remote address. remote ip [192.168.20.10] port [7790]. errno [67] error description [Address already in use]')
    li.append('|.1.3.6.1.4.1.193.176.50.2.5|5|07:df:0a:07:0e:14:01:00:2b:08:00|Failed to establish X2 connection|3|licId01|Cannot connect to X2 remote address. remote ip [192.168.20.10] port [7790]. errno [67] error description [Address already in use]')
    
    #i = 0
    while(True):
        #if(datetime.datetime.now().minute % 5 == 0):
        if(True):
            log0.info('Will start to generate big alarm files.')
            endTime = datetime.datetime.now()
            startTime = endTime + timedelta(minutes = -5)
            fileName = "Alarm." + startTime.strftime('%Y%m%d.%H%M') + '+0800-' + endTime.strftime('%H%M') + '.txt'
            exportPath = os.path.normpath('/xcom/alarm' + os.path.sep + fileName)
            
            try:
                if(os.path.isfile(exportPath)):
                    log0.warn('The file with name: ' + exportPath + ' already exists, the script will try to delete it.')
                    os.remove(exportPath)
                if(not os.path.isdir('/xcom/alarm')):
                    log0.warn('Try to create the directory: /xcom/alarm')
                    os.makedirs('/xcom/alarm')
                f = open(exportPath, 'w')
                i = 0
                while(i < limit):
                    tNow = datetime.datetime.now()
                    fStr = tNow.strftime('%Y%m%d%H%M%S')
                    tStr = tNow.strftime('%Y-%m-%d %H:%M:%S')
                    u, h = CommonFunc.getHexFromStr(tStr)
                    h = ':'.join(h[o:o+2] for o in range(0, len(h), 2))
                    j = 0
                    while(j < 1000):
                        for p in range(0, 5):
                            li[p] = fStr + str(counter) + '|.1.3.6.1.4.1.193.176.50.2.5|' + str(p + 1) + '|' + h + '|Failed to establish X2 connection|3|licId01|Cannot connect to X2 remote address. remote ip [192.168.20.10] port [7790]. errno [67] error description [Address already in use]\n'
                            i += 1
                            j += 1
                            counter += 1
                            if(counter > 4294967296):
                                counter = 1            
                        f.writelines(li)
                    #print "Write 1000 record, total number: " + str(i)
                    f.flush()
                f.close()
            except Exception as e:
                log0.error(str(e))
            log0.info('Finish to write the alarm big files.')
            time.sleep(10 - datetime.datetime.now().second % 10)
        time.sleep(10)
        log0.info('Sleep 10 seconds to check if will write file again.')