#!/usr/bin/python
# -*- coding: utf-8 -*-
__version__ = '0.4'

##----PACKAGE------##
import argparse
import time
import sys
import os
from argparse import RawTextHelpFormatter
from pkg_resources import resource_filename
from multiprocessing import Pool
import urllib2
import random
import cookielib
import math
import datetime

##----MAIN---------##
def main():
	args_raw = get_args()

	if args_raw.which == 'hero':
		run_mode_hero(args_raw)

	elif args_raw.which == 'player':
		run_mode_player(args_raw)

	elif args_raw.which == 'team':
		run_mode_team(args_raw)

##----CODA---------##
	make_ornament('> END', 100, ' ', 1, 1)
	make_ornament('', 100, '-', 0, 0)
	print ('\t|' + ' '*47 + '__.' + ' '*48 + '|\n'
'\t|' + ' '*32 + '___.  ____.   |  |  __. __.__.   __.' + ' '*30 + '|\n'
'\t|' + ' '*30 + '_/ ___\ \__  \  |  | <   y  |\  \ /  /' + ' '*30 + '|\n'
'\t|' + ' '*30 + '\  c___  /  a \_|  l__\___  | >  x  <' + ' '*31 + '|\n'
'\t|' + ' '*31 + '\_____>(______/|____//_____|/__/ \__\\' + ' '*30 + '|\n'
'\t|' + '~'*42 + 'www.calyx.biz' + '~'*43 + '|\n')

##----FUNCTION-----##
#---get args---
def get_args():
	tool = os.path.basename(sys.argv[0])
	author = 'Yamol'
	email = 'xlccalyx@qq.com'
	date = 'Apr 26, 2016'
	update_date = ''
	home = 'www.calyx.biz'

	parser = argparse.ArgumentParser(description='\ttool:   ' + tool + ' v' + __version__ + '\n\tdate:   ' + date + '\n\tauthor: ' + author + ' (' + email + ')\n\thome:   ' + home + '\n', prog=tool, formatter_class=RawTextHelpFormatter)

	parser.add_argument('-V', '--version', action='version', version='%(prog)s v' + __version__)

	subparser = parser.add_subparsers(help='select 1 of 3 modes! dota2win hero/player/team -h for further help!')

#---subparser for mode hero
	subparser_hero = subparser.add_parser('hero', help='mode hero, for hero pick strategy.')
	subparser_hero.set_defaults(which='hero')
	subparser_hero.add_argument('-P', '--prepare', help='download all data.', default=False, action='store_true')
	subparser_hero.add_argument('-R', '--refresh', help='refresh all data.', default=False, action='store_true')
	subparser_hero.add_argument('-D', '--default', help='set default value.', default=False, action='store_true')
	subparser_hero.add_argument('-I', '--infor', help='create and show the dota2 hero information.', default=False, action='store_true')
	subparser_hero.add_argument('-A', '--anti', help='anti-hero names, separate names by \',\'.', default='')
	subparser_hero.add_argument('-C', '--comb', help='comb-hero names, separate names by \',\'.', default='')
	subparser_hero.add_argument('-S', '--skill', help='skill type, default: h, (all, pro, vh, n).', default='h')
	subparser_hero.add_argument('-L', '--ladder', help='ladder type, default: y, (all, n).', default='y')
	subparser_hero.add_argument('-T', '--time', help='time type, default: month, (week, all, v686, v685, v684).', default='month')
	subparser_hero.add_argument('-E', '--server', help='server type, default: world, (cn, all).', default='world')

#---subparser for mode player
	subparser_player = subparser.add_parser('player', help='mode player, to aim at against player.')
	subparser_player.set_defaults(which='player')
	subparser_player.add_argument('-I', '--infor', help='get and show the dota2 player information.', default=False, action='store_true')
	subparser_player.add_argument('-R', '--refresh', help='refresh all data.', default=False, action='store_true')
	subparser_player.add_argument('-P', '--player', help='player steam unique ID. or file contains players\'s steam unique IDs.', default='')
	subparser_player.add_argument('-N', '--number', help='number of match, default: 100.', default=100)

#---subparser for mode team
	subparser_team_raw = subparser.add_parser('team', help='mode team, to aim at against team.')
	subparser_team_raw.set_defaults(which='team')
	subparser_team = subparser_team_raw.add_mutually_exclusive_group()
	subparser_team.add_argument('-I', '--infor', help='get and show the dota2 team information.', default=False, action='store_true')
	subparser_team.add_argument('-A', '--anti', help='anti-team name.')

#	args_dict = {'anti':'宙斯,幽鬼,虚空假面', 'comb':'祈求者,帕吉', 'skill':'h', 'ladder':'y', 'time':'month', 'server':'world'}
	args = parser.parse_args()
#	args = get_class_from_dict(**args_dict)

#---head
	print '\n\t' + ' '.join(sys.argv[:]) + '\n'
	make_ornament('', 100, '-', 0, 0)
	make_ornament('tool:   ' + tool + ' v' + __version__, 100, ' ', 0, 0)
	make_ornament('author: ' + author + ' (' + email + ')', 100, ' ', 0, 0)
	make_ornament('', 100, '-', 0, 0)
	make_ornament('> BEGIN', 100, ' ', 1, 1)

	return args

#---run mode hero---
def run_mode_hero(args_raw):
	dota2win_dir = make_dir(os.getcwd() + '/dota2win/')
	hero_dir = make_dir(dota2win_dir + 'hero/')
	hero_log_dir = make_dir(hero_dir + 'log/')
	hero_data_dir = make_dir(hero_dir + 'data/')
	hero_name_file = resource_filename('dota2win', 'dota2.hero.name.txt')
	hero_name = open(hero_name_file, 'rU').readlines()
	#hero_name = open('/home/tongji1/data/liyx/dota2/dota2win/dota2.hero.name.txt', 'rU').readlines()
	hero_name_split = [[y.lower() for y in x.rstrip().split('\t')] for x in hero_name]
	hero_id_all = [x[0] for x in hero_name_split]
	args = run_preset_hero(hero_log_dir, args_raw)

	if args.infor:
		os.system('cp ' + hero_name_file + ' ' + os.getcwd())
		make_ornament('dota2.hero.name.txt created! check current directory!', 100, ' ', 1, 0)

	elif args.prepare:
		if args.refresh:
			hero_data_old_dir = make_dir(dota2win_dir + 'hero/old_data/')
			os.system('mv ' + hero_data_dir[:-1] + ' ' + hero_data_old_dir + time.strftime("%m%d%y", time.localtime()))
		run_prepare_hero(hero_data_dir, hero_id_all, args)

	elif args.default:
		run_hero_default(hero_dir, args_raw)

	else:
		#anti = '宙斯,幽鬼,虚空假面'
		hero_id_anti = get_hero_id_type(hero_name_split, args.anti, 'anti')

		#comb = '祈求者,帕吉'
		hero_id_comb = get_hero_id_type(hero_name_split, args.comb, 'comb')

		make_ornament('', 100, ' ', 0, 0)
		get_best_hero_pick(hero_id_all, hero_id_anti, hero_id_comb, hero_dir, args, dota2win_dir)

#---run preset hero--
def run_preset_hero(hero_log_dir, args_raw):
	hero_default_file = hero_log_dir + 'hero.default.txt'
	if not os.path.isfile(hero_default_file):
		return args_raw
	else:
		sys_argv = sys.argv[:]
		hero_default = dict([x.split() for x in open(hero_default_file, 'rU').readlines()])
#		args_dict = {'version':__version__, 'prepare':args_raw.prepare, 'refresh':args_raw.refresh, 'default':args_raw.default, 'infor':args_raw.infor, 'anti':args_raw.anti, 'comb':args_raw.comb, 'skill':hero_default['skill'], 'ladder':hero_default['ladder'], 'time':hero_default['time'], 'server':hero_default['server']}
		args_dict = dict(zip(['version', 'prepare', 'refresh', 'default', 'infor', 'anti', 'comb', 'skill', 'ladder', 'time', 'server'], [__version__, args_raw.prepare, args_raw.refresh, args_raw.default, args_raw.infor, args_raw.anti, args_raw.comb, [hero_default['skill'], args_raw.skill]['-S' in sys_argv], [hero_default['ladder'], args_raw.ladder]['-L' in sys_argv], [hero_default['time'], args_raw.time]['-T' in sys_argv], [hero_default['server'], args_raw.server]['-E' in sys_argv]]))
		args = get_class_from_dict(**args_dict)
		return args

#---run prepare hero--
def run_prepare_hero(hero_data_dir, hero_id_all, args):
	for hero_type in ['anti', 'comb']:
		for hero_id in hero_id_all:
			hero_win_score_file = hero_data_dir + '_'.join([hero_type, hero_id, args.skill, args.ladder, args.time, args.server]) + '.txt'
			if not os.path.isfile(hero_win_score_file):
				get_hero_win_score(hero_data_dir, hero_type, hero_id, args)

#---get hero win score--
def get_hero_win_score(hero_data_dir, hero_type, hero_id, args):
	hero_win_score_file = hero_data_dir + '_'.join([hero_type, hero_id, args.skill, args.ladder, args.time, args.server]) + '.txt'
	if not os.path.isfile(hero_win_score_file):
		hero_page_url = 'http://dotamax.com/hero/detail/match_up_%s/%s/?skill=%s&ladder=%s&time=%s&server=%s' % (hero_type, hero_id, args.skill, args.ladder, args.time, args.server)
		url_content = get_url_content(hero_page_url)
		hero_page_infor = url_content.split('<tr><td><a href="/hero/detail/')[1:]
		hero_page_infor_name = [x.split('"><img')[0] for x in hero_page_infor]
		hero_page_infor_score = [x.split('"height: 10px">')[1].split('%</div>')[0] for x in hero_page_infor]
		hero_win_score_raw = [hero_page_infor_name[i] + '\t' + hero_page_infor_score[i] + '\n' for i in range(len(hero_page_infor_name))]
		if hero_type == 'anti':
			hero_win_score_sort = sorted(hero_win_score_raw, key = lambda x:float(x.split()[1]))
		else:
			hero_win_score_sort = sorted(hero_win_score_raw, key = lambda x:float(x.split()[1]), reverse=True)
		write_content(hero_win_score_file, hero_win_score_sort)
	else:
		hero_win_score_sort = open(hero_win_score_file, 'rU').readlines()
	hero_win_score = dict([x.split() for x in hero_win_score_sort])
	make_ornament('_'.join([hero_type, hero_id, args.skill, args.ladder, args.time, args.server]), 100, ' ', 1, 0)
	return hero_win_score

#---run hero default--
def run_hero_default(hero_dir, args):
	hero_default_file = hero_dir + 'hero.default.txt'
	hero_default = 'skill\t%s\nladder\t%s\ntime\t%s\nserver\t%s\n' % (args.skill, args.ladder, args.time, args.server)
	make_ornament('dota2win hero default changed!', 100, ' ', 1, 0)	
	make_ornament('skill = ' + args.skill, 100, ' ', 1, 0)
	make_ornament('ladder = ' + args.ladder, 100, ' ', 1, 0)
	make_ornament('time = ' + args.time, 100, ' ', 1, 0)
	make_ornament('server = ' + args.server, 100, ' ', 1, 0)
	write_content(hero_default_file, hero_default)

#---get hero id type--
def get_hero_id_type(hero_name_split, args_hero_type, type):
	hero_name = args_hero_type.split(',')
	hero_id_raw = [get_hero_id(hero_name_split, x) for x in hero_name]
	for i in range(len(hero_name)):
		make_ornament([type + ' - ', 'WARNING! '][hero_id_raw[i] == 'na'] + hero_name[i] + ': ' + hero_id_raw[i], 100 + [0, len(hero_name[i]) - len(hero_name[i].decode('utf-8'))*2][len(hero_name[i]) != len(hero_name[i].decode('utf-8'))], ' ', 0, 0)
	hero_id = [x for x in hero_id_raw if x != 'na']
	return hero_id

#---get hero id--
def get_hero_id(hero_name_split, any_name):
	hero_id = [x[0] for x in hero_name_split if any_name.lower() in x]
	if len(hero_id) == 1:
		return hero_id[0]
	else:
		return 'na'

#---get best hero pick--
def get_best_hero_pick(hero_id_all, hero_id_anti, hero_id_comb, hero_data_dir, args, dota2win_dir):
	hero_id_all_backup = hero_id_all[:]
	for hero_id in hero_id_anti + hero_id_comb:
		hero_id_all_backup.remove(hero_id)
	best_hero_pick_score = dict(zip(hero_id_all_backup, [[0]]*len(hero_id_all_backup)))
	for hero_id in hero_id_anti:
		hero_win_score = get_hero_win_score(hero_data_dir, 'anti', hero_id, args)
		for x, y in hero_win_score.items():
			if x in best_hero_pick_score.keys():
				best_hero_pick_score[x] = best_hero_pick_score[x] + [-float(y)]
	for hero_id in hero_id_comb:
		hero_win_score = get_hero_win_score(hero_data_dir, 'comb', hero_id, args)
		for x, y in hero_win_score.items():
			if x in best_hero_pick_score.keys():
				best_hero_pick_score[x] = best_hero_pick_score[x] + [float(y)]
	best_hero_pick_table = [str(sum(best_hero_pick_score[x])) + '\t' + x + '\t' + str(sum(best_hero_pick_score[x][1:][:len(hero_id_anti)])) + '\t' + '\t'.join([str(y) for y in best_hero_pick_score[x][1:][:len(hero_id_anti)]]) + '\t' + str(sum(best_hero_pick_score[x][1:][len(hero_id_anti):])) + '\t' + '\t'.join([str(y) for y in best_hero_pick_score[x][1:][len(hero_id_anti):]]) + '\n' for x in best_hero_pick_score.keys()]
	best_hero_pick = ['skill:\t%s\nladder:\t%s\ntime:\t%s\nserver:\t%s\n' % (args.skill, args.ladder, args.time, args.server)] + ['score\tid\tanti_score\tanti>' + '\tanti>'.join(hero_id_anti) + '\tcomb_score\tcomb>' + '\tcomb>'.join(hero_id_comb) + '\n'] + sorted(best_hero_pick_table, key = lambda x:float(x.split()[0]), reverse=True)
	best_hero_pick_file = dota2win_dir + 'hero/' + time.strftime("%m%d%y%H%M%S", time.localtime()) + '.txt'
#	write_content(best_hero_pick_file, best_hero_pick)
	best_hero_pick_sort_all = '\t|\n\t|' + ''.join(best_hero_pick[:20]).replace('\n', '\n\t|')
	best_hero_pick_sort_anti = '\n\t|' + best_hero_pick[1] + '\t|' + ''.join(sorted(best_hero_pick[2:], key = lambda x:float(x.split()[2]), reverse=True)[:15]).replace('\n', '\n\t|')
	print best_hero_pick_sort_all + best_hero_pick_sort_anti

#---run mode player---
#args_raw_dict = {'player': '43276219', 'number':'100', 'refresh':False}
#args_raw = get_class_from_dict(**args_raw_dict)
def run_mode_player(args_raw):
	dota2win_dir = make_dir(os.getcwd() + '/dota2win/')
	player_dir = make_dir(dota2win_dir + 'player/')
	player_log_dir = make_dir(player_dir + 'log/')
	player_data_dir = make_dir(player_dir + 'data/')
	team_infor_file = player_dir + 'dota2.team.player.txt'
	args = args_raw

	if args.infor:
		if not os.path.isfile(team_infor_file) or args_raw.refresh:
			run_team_infor(team_infor_file)
		else:
			make_ornament('WARNING! dota2.team.player.txt exists!', 100, ' ', 0, 0)

	else:
		if args_raw.player != '':
			if os.path.isfile(args_raw.player):
				player_id_all = [x.rstrip() for x in open(args_raw.player, 'rU').readlines()]
				for player_id in player_id_all:
#				player_id = '43276219'
					dota2win_player_command = 'dota2win player -P %s -N %s' % (player_id, args_raw.number)
					run_bash_command(player_log_dir, 'player.%s.%s' % (player_id, args_raw.number), dota2win_player_command)
					make_ornament('player %s, match_number %s.' % (player_id, args_raw.number), 100, ' ', 0, 0)
			else:
				run_player_infor(args_raw, player_data_dir, player_log_dir)

		else:
			make_ornament('ABORT! no player id', 100, ' ', 0, 0)

#---run team infor---
def run_team_infor(team_infor_file):
	team_all_page_url = 'http://www.dotabuff.com/esports/teams'
	team_all_page_content = get_url_content_header(team_all_page_url)
	team_all_page_top_50 = team_all_page_content.split('<tr><td><a href="')[1:51]
	team_page_url_all = ['http://www.dotabuff.com/' + x.split('"><img alt="')[0] for x in team_all_page_top_50]
	team_name_all = [x.split('"><img alt="')[1].split('" title="')[0] for x in team_all_page_top_50]
	team_infor = [''.join([team_name_all[i] + '\t' + x for x in get_team_player_infor(team_page_url_all[i], team_name_all[i])]) for i in range(len(team_all_page_top_50))]
	write_content(team_infor_file, team_infor)

#---get team player infor--
def get_team_player_infor(team_page_url, team_name):
	team_page_content = get_url_content_header(team_page_url)
	team_player_content = team_page_content.split('"r-tab-icon"><a href="/esports/players/')[1:]
	player_id_all = [x.split('"><img alt="')[0] for x in team_player_content]
	player_name_all = [x.split('</a> (active)')[0].split('">')[-1] for x in team_player_content if '</a> (active)' in x]
	team_player_infor = [player_name_all[i] + '\t' + player_id_all[i] + '\n' for i in range(len(player_name_all))]
	make_ornament('team: ' + team_name, 100, ' ', 1, 0)	
	return team_player_infor

#---run player infor---
def run_player_infor(args_raw, player_data_dir, player_log_dir):
#	player_dir = '/Users/liyx/MY/B/NetDisk/Dropbox/Proje/Dota2/test/dota2win/player/'
#	player_dir = '/Users/yingxiangli/MY/B/Dropbox (Personal)/Proje/Dota2/test/dota2win/player/'
	page_number = int(math.ceil(int(args_raw.number)/float(50)))
	player_infor_file = player_data_dir + args_raw.player + '.txt'
	check_date = datetime.datetime.now()
	time_stamp = check_date.strftime('%m-%d-%Y\t%H:%M:%S')
	cookie_file = get_dotamax_cookie_file(player_log_dir, check_date, args_raw, 7)
#	cookie_file = '/Users/yingxiangli/MY/B/Dropbox (Personal)/Proje/Dota2/test/dota2win/player/log/04-27-2016.dotamax_en.cookie'
	match_id = []; match_hero = []; match_time = []; match_result = []; match_level = []
	if os.path.isfile(player_infor_file):
		player_infor = open(player_infor_file, 'rU').readlines()[1:]
	else:
		player_infor = []
	match_id_exist = [x.split()[0] for x in player_infor]

	for number in range(1, (page_number + 1)):
#		number = 1
		player_match_url = 'http://dotamax.com/player/match/%s/?skill=&ladder=&hero=-1&p=%s' % (args_raw.player, number)
		player_match_content = get_url_content_header(player_match_url, cookie_file)
		player_match_page = player_match_content.split("DoNav('/match/detail/")[1:]
		if len(player_match_page) != 50:
			make_ornament('ABORT! can\'t find the player %s information!' % (args_raw.player), 100, ' ', 0, 0)
			break
		else:
			match_id = match_id + [x.split("'")[0] for x in player_match_page]
			match_hero = match_hero + [x.split('/images/heroes/')[1].split('_hphover.png')[0] for x in player_match_page]
			match_time = match_time + [get_time_date(x.split('<div class="fromnow">')[1].lstrip().split(' ago')[0]) for x in player_match_page]
			match_result = match_result + [x.split('important;">')[1].split('</font>')[0] for x in player_match_page]
			match_level = match_level + [x.split('</font></td><td style')[0].split('>')[-1].replace('\n', ' ') for x in player_match_page]
			match_infor = []
			for i in range(len(match_id)):
				if match_id[i] in match_id_exist:
					break
				else:
					match_infor.append(match_id[i] + '\t' + match_hero[i] + '\t' + match_time[i] + '\t' + match_result[i] + '\t' + match_level[i] + '\n')
			player_infor = match_infor + player_infor
			if len(match_infor) != len(match_id):
				make_ornament('ATTENTION! %s information updated!' % (args_raw.player), 100, ' ', 0, 0)
				break
	player_infor = [time_stamp + '\n'] + player_infor
	write_content(player_infor_file, player_infor)
	make_ornament('%s: match_number-%s' % (args_raw.player, len(player_infor) - 1), 100, ' ', 0, 0)
#	dota2win player -P 43276219

#---get dotamax cookie file--
def get_dotamax_cookie_file(log_dir, check_date, args_raw, day_old=7):
	dotamax_cookie_url = 'http://dotamax.com/set_language/?language=en'
	dotamax_cookie_file_name = [x for x in os.listdir(log_dir) if x.endswith('dotamax_en.cookie')]
	if len(dotamax_cookie_file_name):
		cookie_file_date = dotamax_cookie_file_name[0].split('.')[0].split('-')
		if args_raw.refresh or (check_date - datetime.datetime(int(cookie_file_date[2]), int(cookie_file_date[0]), int(cookie_file_date[1]))).days >= day_old:
			os.remove(log_dir + dotamax_cookie_file_name[0])
			dotamax_cookie_file = log_dir + check_date.strftime('%m-%d-%Y') + '.dotamax_en.cookie'
			make_cookie(dotamax_cookie_file, dotamax_cookie_url)
			make_ornament('ATTENTION! cookie is updated! %s' + (['(above %s days old)' % (day_old), '(refresh)'][args_raw.refresh]), 100, ' ', 0, 0)
		else:
			dotamax_cookie_file = log_dir + dotamax_cookie_file_name[0]
			make_ornament('ATTENTION! cookie is good!', 100, ' ', 0, 0)
	else:
		dotamax_cookie_file = log_dir + check_date.strftime('%m-%d-%Y') + '.dotamax_en.cookie'
		make_cookie(dotamax_cookie_file, dotamax_cookie_url)
		make_ornament('ATTENTION! cookie created!', 100, ' ', 0, 0)
	return dotamax_cookie_file

#---get time date--
def get_time_date(time_any):
	check_date = datetime.datetime.now()
	time_any_value = time_any.split(' ')[0] 
	time_any_unit = time_any.split(' ')[1]
	time_unit = {'43200':['month', 'months'], '1440': ['day', 'days'], '60':['hour', 'hours'], '1':['minute', 'minutes']}
	for x, y in time_unit.items():
		if time_any_unit in y:
			time_date = check_date + datetime.timedelta(minutes = -int(time_any_value)*float(x))
	return time_date.strftime('%m-%d-%Y')

#---run player summary---
def run_match_summary(player_infor_part):
	match_hero = [x.split('\t')[1] for x in player_infor_part]
	match_result = [x.split('\t')[3] for x in player_infor_part]
	match_level = [x.split('\t')[4] for x in player_infor_part]
	hero_use = [[x, match_hero.count(x)] for x in set(match_hero)]
	hero_use_sort = sorted(hero_use, key=lambda x:x[1], reverse=True)
	match_hero_summary = ['match_number:\t%s\n' % (len(player_infor_part)), 'hero_use:\t%s\n' % (len(hero_use))]
	for hero, count in hero_use_sort:
		hero_win_ratio = round([match_result[x] for x in get_index_all(match_hero, hero)].count('Won')/float(count), 3)
		match_hero_summary.append('\t'.join([hero, str(count), str(round(float(count)/len(player_infor_part), 3)), str(hero_win_ratio)]) + '\n')
	return match_hero_summary
#print ''.join(run_match_summary(player_infor_part))
	page_number = int(math.ceil(args_raw.number/float(50)))
	player_infor_file_name = args_raw.player + '_' + str(page_number*50)
	player_infor_file = player_data_dir + player_infor_file_name + '.txt'
	player_infor = open(player_infor_file, 'rU').readlines()

#--common--
class get_class_from_dict:
	def __init__(self, **entries): 
		self.__dict__.update(entries)

def add_thousand_separator(int_number):
	return str(format(int(int_number), ','))

def get_absolute_file(file):
	split_file = [x for x in file.split('/') if x != '']
	current_dir = os.getcwd()
	split_current_dir = [x for x in current_dir.split('/') if x != '']
	if len(set(split_file)&set(split_current_dir)) == 0:
		absolute_file = current_dir + '/' + file
	else:
		absolute_file = file
	if os.path.isfile(absolute_file):
		return absolute_file
	else:
		return 'WRONG file or directory!'

def get_index_all(list, element):
	index_all = [i for i,v in enumerate(list) if v==element]
	return index_all

def get_process_time(function_name, is_finish=0, width=100, indent=16):
	function_name_indent = ' '*(indent - len(function_name.split(':')[0])) + function_name
	if is_finish == 0:		
		make_ornament(function_name_indent + ' '*(width - 23 - len(function_name_indent)) + '  -running', width)
	else:
		make_ornament(function_name_indent + ' '*(width - 23 - len(function_name_indent)) + ' -finished', width)

def get_url_content(url):
	pause_time = [1, 2, 3, 4, 5]
	time.sleep(random.choice(pause_time))
	url_content = urllib2.build_opener(urllib2.HTTPCookieProcessor).open(url).read()
	return url_content

def get_url_content_header(url, cookie_file=''):
#	url = 'http://dotamax.com/player/match/43276219/?skill=vh&ladder=&hero=-1&p=1'	
	fake_header = ['Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648)', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; InfoPath.1', 'Mozilla/4.0 (compatible; GoogleToolbar 5.0.2124.2070; Windows 6.0; MSIE 8.0.6001.18241)', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; Sleipnir/2.9.8)']
	pause_time = [1, 2, 3, 4, 5]
	time.sleep(random.choice(pause_time))
	random_header = random.choice(fake_header)
	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor)
#	random_header = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.86 Safari/537.36'
	opener.addheaders = [('User-Agent', random_header)]
	if cookie_file != '':
		cookie = cookielib.MozillaCookieJar()
		cookie.load(cookie_file, ignore_discard=True, ignore_expires=True)
		opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
	url_content = opener.open(url).read()
	#url_content = urllib2.urlopen(urllib2.Request(url)).read()
	return url_content

def make_cookie(cookie_file, url):
	cookie = cookielib.MozillaCookieJar(cookie_file)
	handler = urllib2.HTTPCookieProcessor(cookie)
	opener = urllib2.build_opener(handler)
	response = opener.open(url)
	cookie.save(ignore_discard=True, ignore_expires=True)

#make_cookie('cookie.txt', 'http://dotamax.com/set_language/?language=en')

def make_dir(dir):
	dir = dir.strip().rstrip("\\")
	if not os.path.exists(dir):
		os.makedirs(dir)
	return dir

def make_initial_upper(word):
	initial_upper = word[0].upper() + word[1:].lower()
	return initial_upper

def make_ornament(title, width=100, ornament_type=' ', show_time=1, show_date = 0):
	if show_time == 1:
		if show_date == 0:
			ornament = '\t|' + title + ornament_type*(width - 13 - len(title)) + ' @ ' + time.strftime("%X", time.localtime()) + '|'
		else:
			ornament = '\t|' + title + ornament_type*(width - 24 - len(title)) + ' @ ' + time.strftime("%m-%d-%Y %X", time.localtime()) + '|'
	else:
		ornament = '\t|' + title + ornament_type*(width - 2 - len(title)) + '|'
	print ornament

def run_bash_command(log_dir, command_name, command):
	command_file = make_dir(log_dir) + command_name + '.sh'
	write_content(command_file, command)
	bash_command = 'bash "' + command_file + '" > ' + command_file.replace('.sh', '.log') + ' 2>&1'
	os.system(bash_command)

def write_content(content_file, content):
	output = open(content_file, 'w')
	output.writelines(content)
	output.close()

##----PROCESS------##
if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        sys.stderr.write("User interrupted me! ;-) Bye!\n")
        sys.exit(0)

##----TEST--------##
#	dota2win player -P /Users/yingxiangli/MY/B/Dropbox\ \(Personal\)/Proje/Dota2/test/dota2win/player/player.test.txt -N 100
#	dota2win player -P /Users/liyx/MY/B/NetDisk/Dropbox/Proje/Dota2/test/dota2win/player/player.test.txt -N 100
#	dota2win player -P /Users/liyx/MY/B/NetDisk/Dropbox/Proje/Dota2/test/dota2win/player/player.txt -N 1000
#	dota2win player -P /data/tongji1/liyx/dota2/dota2hero/dota2hero.infor.txt -N 1000