from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
database = 'sqlite:///sqlite.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = database
app.config['SECRET_KEY'] = 'SECRET_KEY'
db = SQLAlchemy()

db.init_app(app)
import datetime
from datetime import datetime
import json

from sqlalchemy.exc import IntegrityError
from werkzeug.security import generate_password_hash, check_password_hash

class Player(db.Model):
    __tablename__ = 'football'

    id = db.Column(db.Integer, primary_key=True)
    _name = db.Column(db.String(255), unique=False, nullable=False)
    _number = db.Column(db.Integer, unique=False, nullable=False)
    _wins = db.Column(db.Integer, unique=False, nullable=False)
    _losses = db.Column(db.Integer, unique=False, nullable=False)

    def __init__(self, name, number, wins, losses):
        self._name = name
        self._number = number
        self._wins = wins
        self._losses = losses

   
    @property
    def name(self):
        return self._name
    
    @name.setter 
    def name(self, name):
        self._name = name
    
    @property
    def number(self):
        return self._number
    
    @number.setter
    def number(self, number):
        self._number = number
    
    @property
    def wins(self):
        return self._wins

    @wins.setter
    def wins(self, wins):
        self._wins = wins 
    
    @property
    def losses(self):
        return self._losses

    @losses.setter
    def losses(self, losses):
        self._losses = losses


    def __str__(self):
        return json.dumps(self.read())

    def create(self):
        try:
            
            db.session.add(self) 
            db.session.commit() 
            return self
        except IntegrityError:
            db.session.remove()
            return None

    def read(self):
        return {
            "id": self.id,
            "name": self.name,
            "number": self.number,
            "wins": self.wins,
            "losses": self.losses,
        }

    def update(self, dictionary):
        for x in dictionary:
            if x == "number":
                self.number = dictionary[x]
            if x == "wins":
                self.wins = dictionary[x]
            if x == "losses":
                self.losses = dictionary[x]
        db.session.merge(self)
        db.session.commit()
        return None

    def delete(self):
        db.session.delete(self)
        db.session.commit()
        return None
def initUsers():
    with app.app_context():
        db.create_all()
        p1 = Player(name='Patrick Mahomes', number='15', wins='64', losses='16')
        p2 = Player(name='JJ Watt', number='99', wins='77', losses='74')
        p3 = Player(name='Russell Wilson', number='3', wins='108', losses='64')
        p4 = Player(name='Travis Kelce', number='87', wins='105', losses='39')
        p5 = Player(name='Joe Burrow', number='9', wins='24', losses='17')
        p6 = Player(name='Trevor Lawrence', number='16', wins='12', losses='22')


        players = [p1, p2, p3, p4, p5, p6]

        for x in players:
            try:
                object = x.create()
                print(f"Created new uid {object.name}")
            except:
                print(f"Records exist uid {x.name}, or error.")
                
initUsers()
Created new uid Patrick Mahomes
Created new uid JJ Watt
Created new uid Russell Wilson
Created new uid Travis Kelce
Created new uid Joe Burrow
Created new uid Trevor Lawrence
def find_by_name(name):
    with app.app_context():
        player = Player.query.filter_by(_name=name).first()
    return player 
def create():
    name = input("Enter your name:")
    player = find_by_name(name)
    try:
        print("Found\n", name.read())
        return
    except:
        pass 
    
    number = input("Enter your number:")
    wins = input("Enter your wins:")
    losses = input("Enter your losses:")
    
    player = Player(name=name, 
                number=number, 
                wins=wins,
                losses=losses
                )
    
    with app.app_context():
        try:
            object = player.create()
            print("Created\n", object.read())
        except:
            print("Unknown error name {name}")
        
create()
Created
 {'id': 17, 'name': 'Kaiden Do', 'number': 50, 'wins': 60, 'losses': 30}
def read():
    with app.app_context():
        table = Player.query.all()
    json_ready = [player.read() for player in table]
    return json_ready

read()
[{'id': 1, 'name': 'Patrick Mahomes', 'number': 15, 'wins': 64, 'losses': 16},
 {'id': 2, 'name': 'JJ Watt', 'number': 99, 'wins': 77, 'losses': 74},
 {'id': 3, 'name': 'Russell Wilson', 'number': 3, 'wins': 108, 'losses': 64},
 {'id': 4, 'name': 'Travis Kelce', 'number': 87, 'wins': 105, 'losses': 39},
 {'id': 5, 'name': 'Joe Burrow', 'number': 9, 'wins': 24, 'losses': 17},
 {'id': 6, 'name': 'Trevor Lawrence', 'number': 16, 'wins': 12, 'losses': 22},
 {'id': 10, 'name': 'Kaiden Do', 'number': 25, 'wins': 1000, 'losses': 10},
 {'id': 11, 'name': 'Patrick Mahomes', 'number': 15, 'wins': 64, 'losses': 16},
 {'id': 12, 'name': 'JJ Watt', 'number': 99, 'wins': 77, 'losses': 74},
 {'id': 13, 'name': 'Russell Wilson', 'number': 3, 'wins': 108, 'losses': 64},
 {'id': 14, 'name': 'Travis Kelce', 'number': 87, 'wins': 105, 'losses': 39},
 {'id': 15, 'name': 'Joe Burrow', 'number': 9, 'wins': 24, 'losses': 17},
 {'id': 16, 'name': 'Trevor Lawrence', 'number': 16, 'wins': 12, 'losses': 22},
 {'id': 17, 'name': 'Kaiden Do', 'number': 50, 'wins': 60, 'losses': 30}]
def put():
    name = str(input("Who do you want to edit?"))
    number = int(input("Enter the player's new number or same number"))
    wins = int(input("Enter the player's new number of wins"))
    losses = int(input("Enter the player's new number of losses"))
    body = {
        "name": name,
        "data": {"number": number, "wins": wins, "losses": losses}
    }
    data = body.get('data')
    player = find_by_name(name)
    with app.app_context():
        player.update(data)
        db.session.commit()
    return f"{player.name} at id {player.id} has been updated"

put()
'Kaiden Do at id 10 has been updated'
def delete():
    name = str(input("Who do you want to delete?"))
    player = find_by_name(name)
    with app.app_context():
        player.delete()
    return f"{player.name} at id {player.id} has been deleted"

delete()
'Kaiden Do at id 10 has been deleted'