from apscheduler.schedulers.background import BackgroundScheduler
from django.conf import settings
import datetime as timeDelta
import string
import random
from django.utils.timezone import datetime
from apscheduler.triggers.cron import CronTrigger


# from gdrive import delete_file, upload_to_google_drive

scheduler = BackgroundScheduler(settings.SCHEDULER_CONFIG)


def getUniqueID():

    # initializing size of string
    N = 7

    # using random.choices()
    # generating random strings
    return "".join(random.choices(string.ascii_uppercase + string.digits, k=N))

def scheduleAnyTask(function, args, seconds=3):
    try:
        now = datetime.now()
        now_plus_3 = now + timeDelta.timedelta(0, seconds)
        __id = getUniqueID()
        print("Job Added")
        trigger = CronTrigger(
            year=now_plus_3.year,
            month=now_plus_3.month,
            day=now_plus_3.day,
            hour=now_plus_3.hour,
            minute=now_plus_3.minute,
            second=now_plus_3.second,
        )

        scheduler.add_job(
            function,
            args=args,
            trigger=trigger,
            id=__id,
            max_instances=1,
            replace_existing=False,
        )
    except Exception as ex:
        print(ex)



def start():
    try:
        if scheduler.state != 1:
            scheduler.start()

        print("Job Started!")

    except Exception as ex:
        print(ex)


def shutdown():
    try:
        scheduler = BackgroundScheduler()
        if scheduler.state == 1:
            scheduler.shutdown()
    except Exception as ex:
        print(ex)
