# File Name: app.py
# Author Name: In-young Choung
# Date: March 1, 2017
# Description: This python file contains database configuration and creates database tables and fields using flask_sqlalchemy.
#              Users' values passed from Javascript are inserted into the database table.
#              It also has mapping request to interact with specific html files and
#              it reads a file of itemlist.text and prints out to the console.

from flask_sqlalchemy import SQLAlchemy
from flask import Flask, render_template, request


# passing the whole app code to Flask
app = Flask(__name__)

# Configuration for Database ORM - database name: grocery app, user: groceryadmin, password: VKov2q3XTtqj6w9o
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://groceryadmin:VKov2q3XTtqj6w9o@localhost/groceryapp'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

# Database instantiation
db = SQLAlchemy(app)

# database ORM calc table - 3 columns
class Calc(db.Model):
    __tablename__="calc"

    # database fields
    id = db.Column(db.Integer, primary_key=True)
    result = db.Column(db.String(64))
    timestampe = db.Column(db.TIMESTAMP)

    # adding constraints to delete all data in Item when calc is deleted.
    item = db.relationship('Item', backref='calc', cascade='all, delete-orphan', lazy='dynamic')


# database ORM item table - 9 columns
class Item(db.Model):
    __tablename__ = "items"

    # database fields
    id = db.Column(db.Integer, primary_key=True)
    item_type = db.Column(db.String(64))
    brand_name = db.Column(db.String(64))
    price = db.Column(db.Integer)
    weight = db.Column(db.Integer)
    weight_type = db.Column(db.String(5))
    discount = db.Column(db.Integer)
    discount_type = db.Column(db.String(20))
    calc_id = db.Column(db.Integer, db.ForeignKey(Calc.id))


# create all the tables defined as classes
db.create_all()


# mapping request to URLs
@app.route('/', methods = ['GET', 'POST'])
def index():
    if request.method == 'GET':
        # renders to html file
        return render_template('index.html')


# end point where python gets user data from javascript
@app.route('/calculate', methods = ['GET'])
def calculate():
    # get value from html
    itemtype = (request.args.get('param1'))
    brandN1 = (request.args.get('param2'))
    brandN2 = (request.args.get('param3'))
    price1 = (request.args.get('param4'))
    price2 = (request.args.get('param5'))
    weight1 = (request.args.get('param6'))
    weightT1 = (request.args.get('param7'))
    weight2 = (request.args.get('param8'))
    weightT2 = (request.args.get('param9'))
    discount1 = (request.args.get('param10'))
    discountT1 = (request.args.get('param11'))
    discount2 = (request.args.get('param12'))
    discountT2 = (request.args.get('param13'))


    #TODO: calculate function
    # total2 = float(total)
    # new_total = 1.0 + total2
    # print(new_total)
    #
    # weight_types = ['lb', 'kg', 'g']
    #
    # item1_byWeight = float(price1) / float(weight1);
    # item2_byWeight = float(price2) / float(weight2);
    #
    # if (item1_byWeight < item2_byWeight) :
    #     difference = float(item2_byWeight) - float(item1_byWeight)
    #     result = (item1 + "is cheapter by " + difference)
    # else :
    #     difference = float(item1_byWeight) - float(item2_byWeight)
    #     result = (item2 + "is cheapter by " + difference)
    #
    # print(param1 + param2)
    # result = param1 + param2

    # returns a row from db
    # item_from_db = Item.query.filter_by(item_type=itemtype).first();

    # if item_from_db is not None:
    #     print("already exists in the database.")
    # else:

    try:
        # define array variables to be ready to match with db columns
        brand_names = [brandN1, brandN2]
        prices = [price1, price2]
        weights = [weight1, weight2]
        weight_types = [weightT1, weightT2]
        discounts = [discount1, discount2]
        discount_types = [discountT1, discountT2]

        # iteration variable for loop
        i = 0

        # loop twice to save two compared items into database
        for i in range(0, 2):
            item = Item(item_type = itemtype, brand_name = brand_names[i], price =prices[i],
                           weight=weights[i] , weight_type = weight_types[i], discount = discounts[i] ,
                           discount_type = discount_types[i])

            # insert a new row into the database
            db.session.add(item)

        # write it to db disk once the loop is done
        db.session.commit()

    # catch the exception and print it
    except ValueError:
        print(ValueError)
        print("failed to create new row")


# File I/O - prints a list of grocery items
path = "C:\In-young Choung\Computer Programming\Self Programming Files\grocerycalc\itemlist.txt"
# open a file for writing and create it if it doesn't exist.
f = open(path,"w+")

# open the file in the defined path and "r" read it
f = open(path, "r")
if f.mode == 'r':
    # use read function to read the entire file.
    contents = f.read()
    #print the file content in the console
    print(contents)


# main method
if __name__ == '__main__':
    app.debug = True
    # app.debug = False
    app.run()
