def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        username = request.form['Username']
        password = request.form['Password']
        cursor = db.cursor()
        sql = "select password from user where name='%s'" % username
        cursor.execute(sql)
        results = cursor.fetchall()
        for row in results:
            pasw = row[0]
            if pasw == password:
                session['username'] = username
                session.permanemt = True
                code = get_db_data(
                    db,
                    'select UserID from User where Name = "%s"' % (username))
                print(code)
                code_value = code[0]
                flash("Your User ID is %s, please record this." % (code_value),
                      "success")
                return redirect(url_for('home'))
            else:
                flash("Username not exist or password error", "danger")
                return redirect(url_for('regist'))
def donation():
    form = DonationForm(request.form)
    if request.method == 'POST' and form.validate():
        # retreive data from user form
        MaterialID = form.MaterialID.data
        QuantityAvailable = form.QuantityAvailable.data
        Expiration = form.Expiration.data
        UserID = form.UserID.data
        TitleID = form.TitleID.data
        Available = form.Available.data
        if int(TitleID) == 15:
            # get old data and for calculation of new total quantity
            old_quantity_total = get_db_data(
                db,
                f'SELECT QuantityTotal FROM Material WHERE MaterialID="{MaterialID}"'
            )
            # update sql db into material table
            sql_new_donation = f'INSERT INTO Donation (MaterialID, QuantityAvailable, Expiration, UserID, TitleID, Available) \
                    VALUES ({MaterialID}, {QuantityAvailable}, "{Expiration}", {UserID}, {TitleID}, "{Available}")'

            sql_update_material = f'UPDATE Material SET QuantityTotal="{int(old_quantity_total[0][0])+int(QuantityAvailable)}" WHERE MaterialID="{MaterialID}"'
            # execute db and notify user
            if execute_sql(db, sql_new_donation) and execute_sql(
                    db, sql_update_material):
                flash(
                    "Thank you. We got your donation information. You will be contacted if there is a match for your donation.",
                    "success")
            else:
                flash(
                    "Submission failed. Please check your fields or debug the code.",
                    "danger")
        else:
            # update sql db into material table
            sql_new_donation = f'INSERT INTO Donation (Expiration, UserID, TitleID, Available) \
            values ("{Expiration}", {UserID}, {TitleID}, "{Available}");'

            # sql_new_donation = f'INSERT INTO Donation (Expiration, UserID, TitleID, Available) \
            #         VALUES ("{Expiration}", {UserID}, {TitleID}, "{Available}")'
            if execute_sql(db, sql_new_donation):
                flash(
                    "Thank you. We got your volunteering information. You will be contacted if there is a match for your expertise.",
                    "success")
            else:
                flash(
                    "Submission failed. Please check your fields or debug the code.",
                    "danger")

        return redirect(
            url_for('home'))  # pass in the function name to url_for
    return render_template('donation.html', data=get_new_data(db), form=form)
def request_match():
    form = Request(request.form)
    if request.method == 'POST' and form.validate():
        # retreive data from user form
        UserID = form.UserID.data
        EventID = form.EventID.data
        MaterialID = form.MaterialID.data
        MaterialQuantity = form.MaterialQuantity.data
        VolunteerQuantity = form.VolunteerQuantity.data
        Deadline = form.Deadline.data
        TitleID = form.TitleID.data
        Address = form.Address.data
        sql_new_request = f'INSERT INTO request (EventID, MaterialID, Quantity, VolunteerQuantity, TitleID, Address, UserID, Deadline, Status) \
                VALUES ({EventID}, {MaterialID}, {MaterialQuantity}, {VolunteerQuantity}, {TitleID}, "{Address}", {UserID}, "{Deadline}", 0);'

        # execute db and notify user
        if execute_sql(db, sql_new_request):
            if match_material(db, MaterialID, MaterialQuantity):
                if match_volunteer(db, TitleID, VolunteerQuantity, Deadline):
                    RequestValue = get_db_data(
                        db,
                        'select RequestID FROM Request where UserID = %s and MaterialID = %s and EventID = %s and TitleID = %s'
                        % (
                            UserID,
                            MaterialID,
                            EventID,
                            TitleID,
                        ))
                    RequestID = RequestValue[0][0]
                    request_match_funct(db, MaterialID, MaterialQuantity,
                                        TitleID, VolunteerQuantity, RequestID,
                                        Deadline)
                    flash("Your request has been matched.", "success")
                else:
                    flash(
                        "No request match, insufficient volunteers available.",
                        "success")
            else:
                flash("No request match. Please review available materials.",
                      "danger")
        else:
            flash(
                "Submission failed. Please check your fields or debug the code.",
                "danger")
        return redirect(url_for('request_match'))

    return render_template('request_match.html',
                           form=form,
                           data=get_new_data(db))
def match_form():
    form = UserIDForm(request.form)
    if request.method == 'POST' and form.validate():
        User = form.User.data
        sql_match_return = 'SELECT DonationID FROM Donation WHERE UserID = %s;' % (
            User)
        don_data = get_db_data(db, sql_match_return)
        don_list = ''
        for items in don_data:
            holder_2 = get_db_data(
                db,
                'Select RequestID, MaterialQuantity FROM Response WHERE DonationID = %s;'
                % (items[0]))
            for itemss in holder_2:
                holder1 = get_db_data(
                    db,
                    'SELECT MaterialID, Address, TitleID FROM Request WHERE RequestID = %s;'
                    % (itemss[0]))
                for itemsss in holder1:
                    don_list = don_list + 'You have been matched to provide %s of material %s and assist as %s at %s. ' % (
                        itemss[1], itemsss[0], itemsss[2], itemsss[1])
        flash(don_list, "success")
        return redirect(url_for('match_form'))
    return render_template('match.html', form=form, data=get_new_data(db))
def event():
    form = Event(request.form)
    if request.method == 'POST' and form.validate():
        # retreive data from user form
        country = form.country.data
        city = form.city.data
        zipcode = form.zipcode.data
        sql_new_event = f'INSERT INTO disaster (country, city, zipcode) \
                VALUES ("{country}", "{city}", "{zipcode}")'

        # execute db and notify user
        if execute_sql(db, sql_new_event):
            flash(
                "You registered a new event/disaster. You can submit your request now.",
                "success")
        else:
            flash(
                "Submission failed. Please check your fields or debug the code.",
                "danger")
        return redirect(url_for('request_match'))
    return render_template('event.html',
                           form=form,
                           data=get_db_data(db, 'select * from disaster;'))