from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import IntegrityError
from datetime import datetime
import json

app = Flask(__name__) 

database = 'sqlite:///inventory.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)

class Item(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    _name = db.Column(db.String(255), unique=True, nullable=False)
    _date = db.Column(db.String(255), unique=False, nullable=False)
    _action = db.Column(db.String(255), unique=False, nullable=False)
    _quantity = db.Column(db.Integer, unique=False, nullable=False)

    def __init__(self, name, date, action, quantity):
        self._name = name
        self._date = date
        self._action = action
        self._quantity = quantity

    @property
    def name(self):
        return self._name
    
    @name.setter
    def name(self, name):
        self._name = name
    
    @property
    def date(self):
        return self._date
    
    @date.setter
    def date(self, date):
        self._date = date
        
    @property
    def action(self):
        return self._action
    
    @action.setter
    def action(self, action):
        self._action = action
        
    @property
    def quantity(self):
        return self._quantity
    
    @quantity.setter
    def quantity(self, quantity):
        self._quantity = quantity
        
    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,
            "date": self.date,
            "action":self.action,
            "quantity": self.quantity
        }
        
    def update(self, name, date, action, quantity):
        self.name = name
        self.date = date
        self.action = action
        self.quantity = quantity
        db.session.add(self)
        db.session.commit()
        return self
        
    def delete(self):
        db.session.delete(self)
        db.session.commit()
        return None
    
def initUsers():
    with app.app_context():
        db.create_all()    
        
        i1 = Item(name="Pencils", date="03-15-2023", action="Shipped", quantity=50)
        i2 = Item(name="Pens", date="12-01-2019", action="Delivered", quantity=3)
        i3 = Item(name="Markers", date="02-05-2020", action="In Transit", quantity=80)
        i4 = Item(name="Highlighters", date="01-15-2022", action="Shipped", quantity=7)
        i5 = Item(name="Crayons", date="03-15-2021", action="Processing", quantity=20)

        items = [i1, i2, i3, i4, i5]
        
        for item in items:
            try:
                object = item.create()
                print(f"Created new item {object.name}")
            except:
                print(f"Records exist item {item.name}, or error.")
         
def dateCheck(date):
    try:
        datetime.strptime(date, "%m-%d-%Y")
        return True
    except ValueError:
        return False
                
def create():
    nameChecked = False
    dateChecked = False
    actionChecked = False
    quantityChecked = False
    
    name = input("Enter the name of the new item")
    
    while nameChecked == False:
        if name == "":
            print("You must enter a name.")
            name = input("Enter the name of the new item")
        else:
            nameChecked = True
            
    date = input("Enter the date of the action")
    
    while dateChecked == False:
        if dateCheck(date):
            dateChecked = True
        else:
            print("Invalid format for the date, please use MM-DD-YYYY (example for may 12, 2022: 05-12-2022)")
            date = input("Enter the date of the action")
          
    action = input("Enter the action")
            
    while actionChecked == False:
        if action == "":
            print("You must enter an action.")
            action = input("Enter the action")
        else:
            actionChecked = True
    
    quantity = input("Enter the quantity of the item")
    
    while quantityChecked == False:
        try:
            quantity = int(quantity)
            quantityChecked = True
        except ValueError:
            print("You must enter a number for quantity.")
            quantity = input("Enter the quantity of the item")
    
    item = Item(name=name, date=date, action=action, quantity=quantity)
    
    with app.app_context():
        try:
            object = item.create()
            print("Created\n", object.read())
        except:
            print(f"Unknown error name {name}")
            

def read():
    jsonData = []
    
    with app.app_context():
        data = Item.query.all()    
    
    for item in data:
        jsonData.append(item.read())
    
    output = json.dumps(jsonData, indent=2)
    print(output)

def update():
    itemCheck = False
    name = input("Enter the name of the item you would like to update:")
    
    while itemCheck == False:
        emptyList = []
    
        with app.app_context():
            data = Item.query.all()
        
        for item in data:
            if item.name == name:
                selected = item
            else:
                emptyList.append(item)
        
        if len(emptyList) == len(data):
            input("Item not found, please enter a valid item name")
        else:
            itemCheck = True
        
    nameChecked = False
    dateChecked = False
    actionChecked = False
    quantityChecked = False
    
    name = input("Enter the new name of the item")
    
    while nameChecked == False:
        if name == "":
            print("You must enter a name.")
            name = input("Enter the new name of the item")
        else:
            nameChecked = True
            
    date = input("Enter the new date of the action")
    
    while dateChecked == False:
        if dateCheck(date):
            dateChecked = True
        else:
            print("Invalid format for the date, please use MM-DD-YYYY (example for may 12, 2022: 05-12-2022)")
            date = input("Enter the new date of the action")
        
    action = input("Enter the new action")
            
    while actionChecked == False:
        if action == "":
            print("You must enter an action.")
            action = input("Enter the new action")
        else:
            actionChecked = True
    
    quantity = input("Enter the new quantity of the item")
    
    while quantityChecked == False:
        try:
            quantity = int(quantity)
            quantityChecked = True
        except ValueError:
            print("You must enter a number for quantity.")
            quantity = input("Enter the new quantity of the item")
    
    with app.app_context():
        try:
            selected.update(name, date, action, quantity)
            print("Updated\n", selected.read())
        except:
            print(f"Unknown error name {name}")

def delete():
    itemCheck = False
    name = input("Enter the name of the item you would like to update:")
    
    while itemCheck == False:
        emptyList = []
    
        with app.app_context():
            data = Item.query.all()
        
        for item in data:
            if item.name == name:
                selected = item
            else:
                emptyList.append(item)
        
        if len(emptyList) == len(data):
            input("Item not found, please enter a valid item name")
        else:
            itemCheck = True

    with app.app_context():
        selected.delete()
        print("Deleted:\n", selected.read())
        
def CRUD(x="0"):
    if x == "bad":
        return
    operation = (input('"' + x + '" is not a valid operation.\n Please only enter: C (Create), R (Read), U (Update), D (Delete)')).lower() if x != "0" else (input("Enter: C (Create), R (Read), U (Update), D (Delete)")).lower()
    if operation == "c" or operation == "create":
        create()
    elif operation == "r" or operation == "read":
        read()
    elif operation == "u" or operation == "update":
        update()
    elif operation == "d" or operation == "delete":
        delete()
    elif len(operation) == 0:
        return
    else:
        CRUD(operation)
        return
    CRUD()
    
CRUD()
You must enter a name.
Invalid format for the date, please use MM-DD-YYYY (example for may 12, 2022: 05-12-2022)
Invalid format for the date, please use MM-DD-YYYY (example for may 12, 2022: 05-12-2022)
Invalid format for the date, please use MM-DD-YYYY (example for may 12, 2022: 05-12-2022)
Invalid format for the date, please use MM-DD-YYYY (example for may 12, 2022: 05-12-2022)
Invalid format for the date, please use MM-DD-YYYY (example for may 12, 2022: 05-12-2022)
Invalid format for the date, please use MM-DD-YYYY (example for may 12, 2022: 05-12-2022)
Invalid format for the date, please use MM-DD-YYYY (example for may 12, 2022: 05-12-2022)
Invalid format for the date, please use MM-DD-YYYY (example for may 12, 2022: 05-12-2022)
Invalid format for the date, please use MM-DD-YYYY (example for may 12, 2022: 05-12-2022)
Invalid format for the date, please use MM-DD-YYYY (example for may 12, 2022: 05-12-2022)
Created
 {'id': 13, 'name': 'fasdfaf', 'date': '03-20-2020', 'action': '123', 'quantity': 123}