import os
import logging
import pymysql
import requests
from time import sleep
from selenium import webdriver
from selenium.webdriver import FirefoxOptions
from http.client import BadStatusLine


HOST = "app"
DB = "db"

options = FirefoxOptions()
options.add_argument("--headless")

try:
    db = pymysql.connect(DB,"root","Phaixe6Ait","Task")
    db.autocommit(True)
    cursor = db.cursor()
except Exception:
    print("DB connection error")


def next_url():
    while True:
        cursor.execute("SELECT * FROM orders WHERE checked = 0 ORDER BY id ASC LIMIT 1")
        row = cursor.fetchone()
        if not row:
            sleep(1)
            continue

        url = row[1]
        cursor.execute("UPDATE orders SET checked = 1 WHERE id = " + str(row[0]))
        db.commit()
        yield str(row[0])

def check_report(id, browser=None):
    if browser is None:
        browser = webdriver.Firefox(firefox_options=options, executable_path='/opt/supbot/geckodriver')

    browser.get('http://%s/' % HOST)
    browser.add_cookie({
        'name': 'flag',
        'value': os.getenv('FLAG'),
        'path': '/',
        'expiry': None
        })
    
    print('Made request to http://' + HOST + '/receipt.php?orderID=' + id)
    browser.get('http://' + HOST + '/receipt.php?orderID=' + id)

def main():
    browser = webdriver.Firefox(firefox_options=options, executable_path='/opt/supbot/geckodriver')
    browser.implicitly_wait(60)
    try:
        while (True):
            for url in next_url():
                for i in range(3):
                    try:
                        print(url)
                        check_report(url, browser)
                        break
                    except BadStatusLine as e:
                        logging.error("Everything is fucked up %s time" % i)
                        continue
                    except Exception as e:
                        logging.exception(e)
                        break
    except BaseException as e:
        logging.exception(e)
        browser.quit()
        db.close()


if __name__ == "__main__":
    main()
