#author : @thematrixsimulation

import logging
from datetime import datetime, timedelta
from dateutil import parser, tz
import pandas as pd
import sqlalchemy as db
from configparser import RawConfigParser
import os
import urllib.parse
import calendar
import json
import requests


config_object = RawConfigParser()
scriptDirectory = os.path.dirname(os.path.realpath(__file__))
settingsFilePath = os.path.join(scriptDirectory, ".config.ini")
config_object.readfp(open(settingsFilePath,"r"))

botinfo = config_object["botinfo"]
telegram_id = botinfo["telegram_id"]
telegram_chat_id = botinfo["telegram_chat_id"]

# database connectino
dbinfo = config_object['mysql_database']
log_file = os.path.join(config_object['logs']['base_log'], 'scheduler.log')


logging.basicConfig(filename=log_file,
                    filemode='a',
                    format='%(asctime)s %(name)s %(levelname)s %(message)s',
                    level=logging.INFO)




def send_telegram_message(message):
    """Sends alert via Telegram"""
    url = "https://api.telegram.org/" + telegram_id + "/sendMessage"
    data = {
        "chat_id": telegram_chat_id,
        "text": message
    }
    try:
        response = requests.request(
            "POST",
            url,
            params=data
        )
        logging.info(response.text)
        telegram_data = json.loads(response.text)
        return telegram_data["ok"]
    except Exception as e:
        logging.info(f"failed with error {e}")
        return False


def activateSchedule(item, now, conn):

    try:

        # activate fixed rotation
        if item['rotation_type'] == 'fixed':
            if (item['start_date'] <= now ) and (item['end_date'] >= now) and not item['kill_switch']:
                    item['status'] = 1
                    sql = """update mediashare_campaign set status='{}'""".format(item['status'])
                    conn.execute(sql)

        # activate daily rotation                     
        elif item['rotation_type'] == 'daily':
            if (parser.parse(item['start_time']) <= now ) and (parser.parse(item['end_time']) >= now) and not item['kill_switch']:
                item['status'] = 1
                sql = """update mediashare_campaign set status='{}'""".format(item['status'])
                conn.execute(sql)


        # activate weekly rotation            
        elif item['rotation_type'] == 'weekly':
            weekday = calendar.day_name[now.weekday()]
            weekdays = item['days_week'].split(',')
            if weekday in weekdays:
                if (parser.parse(item['start_time']) <= now ) and (parser.parse(item['end_time']) >= now) and not item['kill_switch']:
                    item['status'] = 1
                    sql = """update mediashare_campaign set status='{}'""".format(item['status'])
                    conn.execute(sql)

        # do nothing            
        else:
            pass
    
    
    except Exception as e:
        logging.info(f"failed with error {e} while activating {item['campaign_name']} campaign for {item['branch']}")
        send_telegram_message(f"failed with error {e} while activating {item['campaign_name']} campaign for {item['branch']}")
        pass

    
# database connection
cnx = db.create_engine('mysql+pymysql://' + str(dbinfo["username"]) + ':' + urllib.parse.quote(str(dbinfo["password"])) + '@' + str(dbinfo['host']) + ':' + str(dbinfo["port"]) + '/' + str(dbinfo["db"]))
conn = cnx.connect()


# get inactive campaigns
df = pd.read_sql("select * from mediashare_campaign where status='0' and kill_switch='0'", conn)
df_dict = df.to_dict(orient='records')
now = datetime.utcnow()

for item in df_dict:
    activateSchedule(item, now, conn)

conn.close()


