# pip install beautifulsoup4

import logging
import time
import urllib.request
import os.path
import sys
from os.path import basename
from datetime import datetime

from bs4 import BeautifulSoup

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + '/scripts')

import firebase

if __name__ == "__main__":
    start_time = time.clock()

    logging.basicConfig(format='%(asctime)s.%(msecs)03d %(levelname)s %(message)s', datefmt='%Y-%m-%d,%H:%M:%S', level=logging.DEBUG)
    logger = logging.getLogger(__name__)

    logger.info('start')

    url_base = 'https://www.portal.brou.com.uy/cotizaciones/'

    with urllib.request.urlopen(url_base) as response:
        html = response.read().decode('utf8')
        soup = BeautifulSoup(html, 'html.parser')

        # print(soup.prettify())

        buy = soup.select('tr:nth-of-type(3) td:nth-of-type(3)')[0].text.strip().replace(',', '.')
        sale = soup.select('tr:nth-of-type(3) td:nth-of-type(5)')[0].text.strip().replace(',', '.')

        currency = {'buyValue': float(buy), 'saleValue': float(sale), 'date': datetime.utcnow()}

        firebase.sendNotification(currency)

    logger.info('total time {:.3f} secs'.format(time.clock() - start_time))