import re
import csv

from telethon import TelegramClient, events, sync

from messageReader import readMessage
from calc import calcLot

from operator import itemgetter

from order import makeOrder



#API info
api_id = 3215739
api_hash = '2ae75dcac0528a9fa786523608d96c3e'

client = TelegramClient('session_read', api_id, api_hash)

#L2T VIP CHANNEL:
#user_input_channel = -1001389726384
#TESTING
user_input_channel = 'me'

#inform that is running
print('Listening to',user_input_channel)

#key words to look for
subjectFilter = 'Instrument' and 'Stop Loss'

#import balance from MT4 calc.csv file (generated by a recurring script every 5 min)
#acc_file = open('C:\\Users\\rtauler\\AppData\\Roaming\\MetaQuotes\\Terminal\\3E8BD1CBF618BD07B3A24E5C179C88CA\\MQL4\\Files\\Data\\acc.csv', 'r')
acc_file = open('C:\\Users\\rtauler\\Desktop\\acc.csv', 'r')
 
balance = float(acc_file.readline())

#listen to messages from target channel
@client.on(events.NewMessage(chats=user_input_channel))
async def newMessageListener(event):
	#Get message text
	newMessage = event.message.message
	#check if message contains the two keywords defined in subjectFilter
	if subjectFilter in newMessage:
		# print('----ORIGINAL MSG-------')
		# print(newMessage)
		# #extract the data of the message into a list
		# print('----EXTRACTED DATA-----')
		#extract the data of the message into a list
		extData = readMessage(newMessage)
		# print(extData)
		# #extract the specifics in the list
		# print('----CALCULATED LOT-----')

		#calculate the lot size
		opLot = calcLot(extData["Symbol"],balance,float(extData["Risk"]),float(2),float(extData["EntryPrice"]),float(extData["StopLoss"]),float(extData["TakeProfit1"]),'')
		# print(opLot)

		print('---OPERATION------')

		#generate a dict with the balance
		balance_arr = {'Balance':balance}

		#join the data from the order + the balance + the lot calculation
		op = extData | balance_arr | opLot
		print(op)

		#send a message to user 
		await client.send_message('me', str(op))


		#makeOrder(op['Symbol'].upper(),op['RecommendedLotRounded'])

		makeOrder('OPEN',op['Type'],op['Symbol'].upper(),op['EntryPrice'],op['StopLossPips'],op['TakeProfit1Pips'],'L2TVip',op['RecommendedLotRounded'],123456,0)
	else:
		print('##### Unrelated message ######')
		await client.send_message('me', 'unrelated message')

#infinite loop to keep listening the channel
with client:
	client.run_until_disconnected()


