# coding: utf-8
import re
import datetime
import time
import requests
from bs4 import BeautifulSoup

t_re = re.compile(r'(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d)')


def fs(s):
    return str(s).replace('\n', '').replace('\t', '').strip()


def out_html(html):
    with open(r'test.html', 'w', encoding='utf-8') as f:
        f.write(str(html))


def get_list(day, month, hour):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36",
        "Referer": "https://draw.vietlotto.org/analy.php?day={}&month={}&year=2023&hour={}".format(day, month, hour)
    }
    url = 'https://draw.vietlotto.org/analy.php?day={}&month={}&year=2023&hour={}'.format(day, month, hour)
    while True:
        try:
            req = requests.get(url, headers=headers, timeout=10)
            html = BeautifulSoup(req.content.decode(), 'lxml')
            # out_html(html)
            list_right_box = html.find(name='div', attrs={'class': 'list_right_box'})
            items = list_right_box.find_all(name='div', attrs={'class': 'item'})
            if items:
                break
        except Exception as e:
            print(e)
            time.sleep(5)
    l = []
    for item in items:
        t = t_re.findall(item.find(name='div', attrs={'class': 'time'}).text)
        if t:
            t = fs(t[0])

        d = fs(item.find(name='div', attrs={'class': 'date'}).text).replace('-', '')
        n = fs(item.find(name='div', attrs={'class': 'ball'}).text)
        # print(d, n, t)
        l.append([d, n, t])
    return l


def look_get():
    new_l = []

    for i in range(20):
        td = datetime.datetime.today()
        new_td = td - datetime.timedelta(hours=i)
        day = new_td.day
        mon = new_td.month
        hour = new_td.hour

        if len(str(day)) == 1:
            day = '0' + str(day)
        if len(str(mon)) == 1:
            mon = '0' + str(mon)
        if len(str(hour)) == 1:
            hour = '0' + str(hour)

        # """

        l = get_list(month=mon, day=day, hour=hour)
        for j in l:
            new_l.append(j)
            if len(new_l) >= 200:
                print('okok...')
                return new_l
        # """
        print(mon, day, hour)
        time.sleep(2)


if __name__ == "__main__":
    mdhmok = []
    while True:
        ssf = datetime.datetime.today()
        print('Now time:{}-{}-{}'.format(ssf.hour, ssf.minute, ssf.second))
        if ssf.minute % 5 == 0:
            time.sleep(10)
            th = '{}-{}-{}-{}'.format(ssf.month, ssf.day, ssf.hour, ssf.minute)
            if th not in mdhmok:
                mdhmok.append(th)
                ll = look_get()

                f = open(r'/home/wwwroot/www.tvxx.net/data.txt', 'w', encoding='utf-8')
                for l in ll:
                    f.write('{} {} {}\n'.format(l[0], l[1], l[2]))
                f.close()
        print(mdhmok)
        time.sleep(5)
