import requests
from bs4 import BeautifulSoup
import time

#urls
BASE_URL = "http://57.129.45.226:8080/steve"
LOGIN_URL = f"{BASE_URL}/manager/signin"
TRANSACTIONS_URL = f"{BASE_URL}/manager/transactions"
STOP_URL = f"{BASE_URL}/manager/operations/v1.6/RemoteStopTransaction"
UNLOCK_URL = f"{BASE_URL}/manager/operations/v1.6/UnlockConnector"

#authentification
USERNAME = "admin"
PASSWORD = "zeusocpp100761"

#liste des bornes
charge_points = ["ZEUS_B1_ATHENA", "ZEUS_B2_APOLLON", "ZEUS_B3_APHRODITE", "ZEUS_B4_ARTEMIS"]

#identifie utilisateur + session
def authenticate():
    session = requests.Session()
    resp = session.get(LOGIN_URL)
    soup = BeautifulSoup(resp.text, "html.parser")
    csrf_token_login = soup.find("input", {"name": "_csrf"})["value"]

    login_payload = {
        "username": USERNAME,
        "password": PASSWORD,
        "_csrf": csrf_token_login,
    }
    resp = session.post(LOGIN_URL, data=login_payload)

    if "Sign In" in resp.text:
        print("uthentification nok")
        return None
    print("authentification ok")
    return session

#recup transaction en cours sur une borne
def get_active_transaction(session, charge_point):
    resp = session.get(TRANSACTIONS_URL)
    soup = BeautifulSoup(resp.text, "html.parser")

    for row in soup.find_all("tr"):#recherche transac actives
        cells = row.find_all("td")
        if len(cells) > 2 and charge_point in cells[1].text:
            return cells[0].text.strip(), cells[3].text.strip()#transaction_id et id_tag
    
    return None, None

#stop transaction
def stop_transaction(session, charge_point):
    #global bann_tag
    transaction_id, id_tag = get_active_transaction(session, charge_point)
    
    if not transaction_id or not id_tag:
        print(f"pas de transaction en cours sur {charge_point}")
        return

    print(f"stop transaction {transaction_id} sur {charge_point}")

    #envoi requete pour stop la transaction
    resp = session.get(STOP_URL)
    soup = BeautifulSoup(resp.text, "html.parser")
    csrf_token_stop = soup.find("input", {"name": "_csrf"})["value"]

    stop_payload = {
        "transactionId": transaction_id,
        "_csrf": csrf_token_stop
    }
    resp = session.post(STOP_URL, data=stop_payload)
    print(f"stop transac {transaction_id} : {resp.status_code}")

    time.sleep(2)
    new_transaction_id, _ = get_active_transaction(session, charge_point)
    if new_transaction_id == transaction_id:
        print(f"error transac {transaction_id} stpo nok")
    else:
        print(f"transac {transaction_id} stop ok")

    #deverouille connecteur
    resp = session.get(UNLOCK_URL)
    soup = BeautifulSoup(resp.text, "html.parser")
    csrf_token_unlock = soup.find("input", {"name": "_csrf"})["value"]

    unlock_payload = {
        "chargePointSelectList": f"V_16_JSON;{charge_point};-",
        "_chargePointSelectList": "1",
        "connectorId": "1",
        "_csrf": csrf_token_unlock
    }
    resp = session.post(UNLOCK_URL, data=unlock_payload)
    print(f"conn déverrouillé {resp.status_code}")
    time.sleep(2)

#stop les transactions en cours
def stop_all(session, cp):
    session = authenticate()
    if session:
        for cp in charge_points:
            stop_transaction(session, cp)

session = authenticate()

if not session or not session.cookies:
    session = authenticate()
    if not session:
        time.sleep(5)
if session:
    for cp in charge_points:
        stop_all(session, cp)