import json
from datetime import datetime

import config
from telethon import TelegramClient, events
import mysql.connector
from telethon.tl.types import MessageEntityUrl
import MySQLdb
from sys import platform

api_id = config.api_id
api_hash = config.api_hash
database = config.database
user = config.user
password = config.password
host = config.host

client = TelegramClient('name', api_id, api_hash)
print("start")

if platform == "linux" or platform == "linux2":
    print("Running on linux\n")
    mysqlDbConnect = MySQLdb

elif platform == "win32":
    print("Running on windows\n")
    mysqlDbConnect = mysql.connector
else:
    print("unsupported OS")
    exit(1)

mysqldb = MySQLdb.connect(user=user, passwd=password,
                          host=host,
                          db=database)



@client.on(events.NewMessage)
async def my_event_handler(event):
    now = datetime.now()
    dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
    print("incoming message: "+dt_string)

    dbcursor = mysqldb.cursor()
    for entity in event.message.get_entities_text(MessageEntityUrl):
        print(entity)

    if hasattr(event.peer_id, 'user_id'):
        id_str = event.peer_id.user_id
    if hasattr(event.peer_id, 'channel_id'):
        id_str = event.peer_id.channel_id

    link = "https://t.me/c/" + str(id_str) + "/" + str(event.message.id)
	

    element_id = str(id_str) + '_' + str(event.message.id)

    # event.message.peer_id+'_'.event.message.id

    dict_item = {'id_str': element_id, 'text': event.message.text, 'date': str(event.date),
                 'channel': id_str, 'link': link}
    str_sql = json.dumps(dict_item)

    # Use all the SQL you like
    dbcursor.execute("INSERT into raw_stream_data(element_id, source, data) VALUES(%s, 7, %s)",
                     (element_id, str_sql))
    mysqldb.commit()


print("connected - start fetching data")

client.start()
client.run_until_disconnected()
mysqldb.close()
