import json
from bs4 import BeautifulSoup
import requests
from db import connection
from sqlalchemy.sql import text
import datetime
import os
import boto3
from config import AWS_ID, AWS_KEY, METEOBLUE_LOGIN, METEOBLUE_PWD

def login(req):
    req.post('https://www.meteoblue.com/en/user/login/index', {"gdpr_form_id:": ""})
    html = req.get('https://www.meteoblue.com/en/user/login/index').content
    soup = BeautifulSoup(html, features='html.parser')
    csrf = soup.find('input', {'id': 'csrf'})
    csrf_name = csrf.attrs.get('name')
    csrf_pass = csrf.attrs.get('value')
    req.post('https://www.meteoblue.com/en/user/login/index', data={
        "username": METEOBLUE_LOGIN,
        "password": METEOBLUE_PWD,
        "remember": "1",
        csrf_name: csrf_pass
    }, headers={
        "authority": "www.meteoblue.com",
        "pragma": "no-cache",
        "cache-control": "no-cache",
        "sec-ch-ua": '"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"',
        "sec-ch-ua-mobile": "?0",
        "upgrade-insecure-requests": "1",
        "origin": "https://www.meteoblue.com",
        "content-type": "application/x-www-form-urlencoded",
        "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36",
        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
        "sec-fetch-site": "same-origin",
        "sec-fetch-mode": "navigate",
        "sec-fetch-user": "?1",
        "sec-fetch-dest": "document",
        "referer": "https://www.meteoblue.com/en/user/login/index",
        "accept-language": "ru-RU,ru;q=0.9",
    })


def getGraph(req, url):
    html = req.get(url).content
    soup = BeautifulSoup(html, features="html.parser")
    download = soup.find('a', {'id': 'chart_download'})
    # print(f"link to download: {download}")
    return 'https:' + download.attrs.get('href').strip()


def saveImage(src, forecast_id, filename, resource_id, client):
    path = f"device_resources/device{forecast_id}/{filename.replace(' ', '_')}.jpg"
    # s3Path = f"device-resources/{forecast_id}_{filename.replace(' ', '_')}.jpg"
    uploadPath = "storage/app/public/"
    os.makedirs(os.path.dirname(uploadPath + path), exist_ok=True)
    response = requests.get(src)
    with open(uploadPath + path, "wb") as f:
        f.write(response.content)

    client.upload_file(uploadPath + path, 'amudario.images',  path)
    connection().execute(text("UPDATE device_resources SET url = :img, updated_at = :updated WHERE id = :id"),
                         updated=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), id=resource_id, img=path)

def run():
    req = requests.Session()
    login(req)
    devices = connection().execute(
        "SELECT id, name, ST_X(geolocation) 'lat', ST_Y(geolocation) 'lng', asl FROM devices WHERE device_type='Meteostation'"
    )
    botoSess = boto3.session.Session()
    client = botoSess.client('s3',
                             region_name='fra1',
                             endpoint_url='https://fra1.digitaloceanspaces.com',
                             aws_access_key_id=AWS_ID,
                             aws_secret_access_key=AWS_KEY)

    for device in devices.all():
        print(f"Device: {device['name']}")
        additional = f'{device["lat"]}N{device["lng"]}E{device["asl"]}'
        resources = connection().execute(text('SELECT * FROM device_resources WHERE device_id = :id'),
                                         id=device["id"])
        for resource in resources.all():
            try:
                url = json.loads(resource['settings'])['url'] + additional
                print(f"resource url: {url}")
                saveImage(getGraph(req, url), device['id'], resource['name'], resource['id'], client)
            except Exception as e:
                print(f"Error: {e}")



if __name__ == '__main__':
    run()
