from werkzeug.security import generate_password_hash, check_password_hash
import json
from datetime import date
import requests

def calculate_age(born):
    today = date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

class User:
    def __init__(self, name, classOf, dob, uid, password):
        self._name = name
        self._uid = uid
        self._dob = dob
        self._classOf = classOf
        self.set_password(password)

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, name):
        self._name = name

    @property
    def uid(self):
        return self._uid

    @uid.setter
    def uid(self, uid):
        self._uid = uid

    @property
    def dob(self):
        return self._dob

    @dob.setter
    def dob(self, dob):
        self._dob = dob

    @property
    def classOf(self):
        return self._classOf

    @classOf.setter
    def classOf(self, classOf):
        self._classOf = classOf

    def is_uid(self, uid):
        return self._uid == uid

    @property
    def password(self):
        return self._password[0:8] + "..."

    def set_password(self, password):
        self._password = generate_password_hash(password, method="sha256")

    def is_password(self, password):
        result = check_password_hash(self._password, password)
        return result

    def toJSON(self):
        excluded_fields = ["_password", "_dob"]
        return json.dumps(
            {
                k[1:]: v
                for k, v in self.__dict__.items()
                if k not in excluded_fields
            }
            | {"age": calculate_age(self._dob)},
            cls=DateTimeEncoder,
        )

    def __str__(self):
        return f'name: "{self.name}", class of: {self.classOf}, id: "{self.uid}", psw: "{self.password}"'

    def __repr__(self):
        return f"Person(name={self._name}, classOf={self._classOf}, uid={self._uid}, password={self._password})"

def tester(users, uid, psw):
    result = None
    for user in users:
        if user.is_uid(uid) and user.is_password(psw):
            print("* ", end="")
            result = user
        print(str(user))
    return result

class DateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, date):
            return obj.isoformat()

"""
The point of this class is to store the name, team, standings, points, nationality, likes, dislikes, and comments for a driver instance
"""
class Driver:

  def __init__(self, driver_name, team_name, position, points, nationality):
    self._name = driver_name
    self._team = team_name
    self._standings = position
    self._points = points
    self._nationality = nationality

    self._likes = 0
    self._dislikes = 0
    self._comments = []

    """
    example comment
    {
      "name": "Sean"
      "message": "This driver is insane!!"
    }
    """

  @property
  def name(self):
    return self._name

  @property
  def team(self):
    return self._team

  @property
  def standings(self):
    return self._standings

  @property
  def nationality(self):
    return self._nationality

  @property
  def likes(self) -> int:
    return self._likes

  @property
  def dislikes(self) -> int:
    return self._dislikes

  @property
  def comments(self) -> list:
    return self._comments

  def incrementLikes(self):
    self._likes += 1

  def incrementDislikes(self):
    self._dislikes += 1

  def addComment(self, comment: dict):
    self._comments.append(comment)

  @comments.getter
  def comments(self):
    return self._comments

if __name__ == "__main__":

    #############################
    # USER TINGS
    #############################

    u1 = User(
        name="Thomas Edison",
        classOf=2024,
        dob=date(2022, 12, 25),
        uid="toby",
        password="123toby",
    )
    u2 = User(
        name="Nicholas Tesla",
        classOf=2025,
        dob=date(2021, 1, 7),
        uid="nick",
        password="123nick",
    )
    u3 = User(
        name="Alexander Graham Bell",
        classOf=2024,
        dob=date(2020, 10, 18),
        uid="lex",
        password="123lex",
    )
    u4 = User(
        name="Eli Whitney",
        classOf=2026,
        dob=date(2019, 9, 16),
        uid="eli",
        password="123eli",
    )
    u5 = User(
        name="Hedy Lemarr",
        classOf=2027,
        dob=date(2018, 3, 12),
        uid="hedy",
        password="123hedy",
    )

    users = [u1, u2, u3, u4, u5]

    print("Test 1: find user 3")
    u = tester(users, u3.uid, "123lex")

    print("\nTest 2: change user 3")
    u.name = "John Mortensen"
    u.uid = "jm1021"
    u.set_password("123qwerty")
    u = tester(users, u.uid, "123qwerty")

    print("\nTest 3: generate JSON")
    json_strings = [u.toJSON() for u in users]
    print("\n".join(json_strings))

    #############################
    # DRIVER TINGS
    #############################

    headers = {
      "X-RapidAPI-Key": "9275b62a1fmsh3b832340dafb492p1abc77jsn58ef554feee6",
   	  "X-RapidAPI-Host": "f1-live-motorsport-data.p.rapidapi.com"
    }

    r = requests.get(
        url="https://f1-live-motorsport-data.p.rapidapi.com/drivers/standings/2022", headers=headers)

    if r.status_code != 200:
      print("API Request failed:", r.status_code)
      exit

    all_drivers = r.json()['results']

    demo_drivers = all_drivers[:4]

    driver_objects = []

    for driver in demo_drivers:
      driver_objects.append(
          Driver(driver_name=driver["driver_name"], team_name=driver["team_name"],
                position=driver["position"], points=driver["points"], nationality=driver["nationality"])
      )

    print("\nDriver objects:")
    print(str(driver_objects))

    print("\nTest 4: add comments & likes")
    driver_objects[0].addComment({
      "name": "Dontavious",
      "message": "You're trash!!"
      })
    [driver_objects[0].incrementDislikes() for i in range(20)]

    print(f"\n  Comments: {driver_objects[0].comments}\n  Likes: {driver_objects[0].likes}\n  Dislikes: {driver_objects[0].dislikes}")

    driver_objects[1].addComment({
      "name": "Dontavious",
      "message": "Mid tbh"
      })
    [driver_objects[1].incrementLikes() for i in range(20)]

    print(f"\n  Comments: {driver_objects[1].comments}\n  Likes: {driver_objects[1].likes}\n  Dislikes: {driver_objects[1].dislikes}")

    
    driver_objects[2].addComment({
      "name": "Dontavious",
      "message": "2.7/3.0: Nice effort, poor execution."
      })
    [driver_objects[2].incrementLikes() for i in range(3)]
    
    print(f"\n  Comments: {driver_objects[2].comments}\n  Likes: {driver_objects[2].likes}\n  Dislikes: {driver_objects[2].dislikes}")
Test 1: find user 3
name: "Thomas Edison", class of: 2024, id: "toby", psw: "sha256$7..."
name: "Nicholas Tesla", class of: 2025, id: "nick", psw: "sha256$n..."
* name: "Alexander Graham Bell", class of: 2024, id: "lex", psw: "sha256$N..."
name: "Eli Whitney", class of: 2026, id: "eli", psw: "sha256$N..."
name: "Hedy Lemarr", class of: 2027, id: "hedy", psw: "sha256$1..."

Test 2: change user 3
name: "Thomas Edison", class of: 2024, id: "toby", psw: "sha256$7..."
name: "Nicholas Tesla", class of: 2025, id: "nick", psw: "sha256$n..."
* name: "John Mortensen", class of: 2024, id: "jm1021", psw: "sha256$t..."
name: "Eli Whitney", class of: 2026, id: "eli", psw: "sha256$N..."
name: "Hedy Lemarr", class of: 2027, id: "hedy", psw: "sha256$1..."

Test 3: generate JSON
{"name": "Thomas Edison", "uid": "toby", "classOf": 2024, "age": 0}
{"name": "Nicholas Tesla", "uid": "nick", "classOf": 2025, "age": 2}
{"name": "John Mortensen", "uid": "jm1021", "classOf": 2024, "age": 2}
{"name": "Eli Whitney", "uid": "eli", "classOf": 2026, "age": 3}
{"name": "Hedy Lemarr", "uid": "hedy", "classOf": 2027, "age": 4}

Driver objects:
[<__main__.Driver object at 0x000001B4620949A0>, <__main__.Driver object at 0x000001B4632BCFA0>, <__main__.Driver object at 0x000001B4639B2530>, <__main__.Driver object at 0x000001B4639B3D30>]

Test 4: add comments & likes

  Comments: [{'name': 'Dontavious', 'message': "You're trash!!"}]
  Likes: 0
  Dislikes: 20

  Comments: [{'name': 'Dontavious', 'message': 'Mid tbh'}]
  Likes: 20
  Dislikes: 0

  Comments: [{'name': 'Dontavious', 'message': '2.7/3.0: Nice effort, poor execution.'}]
  Likes: 3
  Dislikes: 0

Full output

Test 1: find user 3 name: "Thomas Edison", class of: 2024, id: "toby", psw: "sha256$5..." name: "Nicholas Tesla", class of: 2025, id: "nick", psw: "sha256$Y..."

  • name: "Alexander Graham Bell", class of: 2024, id: "lex", psw: "sha256$w..." name: "Eli Whitney", class of: 2026, id: "eli", psw: "sha256$c..." name: "Hedy Lemarr", class of: 2027, id: "hedy", psw: "sha256$m..."

Test 2: change user 3 name: "Thomas Edison", class of: 2024, id: "toby", psw: "sha256$5..." name: "Nicholas Tesla", class of: 2025, id: "nick", psw: "sha256$Y..."

  • name: "John Mortensen", class of: 2024, id: "jm1021", psw: "sha256$M..." name: "Eli Whitney", class of: 2026, id: "eli", psw: "sha256$c..." name: "Hedy Lemarr", class of: 2027, id: "hedy", psw: "sha256$m..."

Test 3: generate JSON {"name": "Thomas Edison", "uid": "toby", "classOf": 2024, "age": 0} {"name": "Nicholas Tesla", "uid": "nick", "classOf": 2025, "age": 2} {"name": "John Mortensen", "uid": "jm1021", "classOf": 2024, "age": 2} {"name": "Eli Whitney", "uid": "eli", "classOf": 2026, "age": 3} {"name": "Hedy Lemarr", "uid": "hedy", "classOf": 2027, "age": 4}

Driver objects: [<main.Driver object at 0x000001B4620E0AC0>, <main.Driver object at 0x000001B46398ECB0>, <main.Driver object at 0x000001B46398EBC0>, <main.Driver object at 0x000001B46398C2E0>]

Test 4: add comments & likes

Comments: [{'name': 'Dontavious', 'message': "You're trash!!"}] Likes: 0 Dislikes: 20

Comments: [{'name': 'Dontavious', 'message': 'Mid tbh'}] Likes: 20 Dislikes: 0

Comments: [{'name': 'Dontavious', 'message': '2.7/3.0: Nice effort, poor execution.'}] Likes: 3 Dislikes: 0 ```