import asyncio
import logging
from datetime import datetime, timezone

try:
    import websockets
except ModuleNotFoundError:
    print("This example relies on the 'websockets' package.")
    print("Please install it by running: ")
    print()
    print(" $ pip install websockets")
    import sys

    sys.exit(1)


from ocpp.v16 import ChargePoint as cp
from ocpp.v16 import call
from ocpp.v16.enums import RegistrationStatus, ChargingProfilePurposeType, ChargingRateUnitType

logging.basicConfig(level=logging.INFO)


class ChargePoint(cp):
    async def send_boot_notification(self):
        request = call.BootNotification(
            charge_point_model="Optimus", charge_point_vendor="The Mobility House"
        )

        response = await self.call(request)

        if response.status == RegistrationStatus.accepted:
            print("Connected to central system.")

    async def send_start_transaction(self):
        request = call.StartTransaction(
            connector_id=1,
            id_tag="ABC123456",  # Example RFID/tag ID
            meter_start=0,
            timestamp=datetime.now(timezone.utc).isoformat()
        )

        response = await self.call(request)

        if response.id_tag_info['status'] == 'Accepted':
            print(f"Charging session started! Transaction ID: {response.transaction_id}")
        else:
            print(f"StartTransaction rejected: {response.id_tag_info['status']}")


async def main():
    async with websockets.connect(
        "ws://localhost:9000/CP_1", subprotocols=["ocpp1.6"]
    ) as ws:

        cp = ChargePoint("CP_1", ws)

        await asyncio.gather(
            cp.start(),
            cp.send_boot_notification(),
            cp.send_start_transaction(),  # Add this line
        )


if __name__ == "__main__":
    # asyncio.run() is used when running this example with Python >= 3.7v
    asyncio.run(main())
