#Importing the application and the database
from app import app, db
#Importing the neccessry flask modules
from flask import request, jsonify
#Importing the current_user function from the flask_login module
from flask_login import current_user
#Importing the neccessary database from the app.models file
from app.models import Incidence, User, Notifications, Comment
#The secrets module will be used to generate random values
import secrets
#importing the os module
import os
"""Importing the Image module from Pillow package
to handle image manipulations"""
from PIL import Image

"""The mark_safe module will recieve an id from Jquery,
then uses it to query the
Incidence database, and marks the user safe of that incidence"""
@app.route("/mark_safe", methods=["POST"])
def mark_safe():
	#Querying the incidence database using the id recieved from Jquery
	incidence = Incidence.query.filter_by(id=request.form['incidence_id']).first()
	current_user.mark(incidence)
	db.session.commit()
	"""Returning jsonify does nothing much, 
	we just use it to stop the server from throwing an error."""
	return jsonify({'success':'true'})

"""Works the same as the mark_Safe module, only that this time it
marks the user unsafe."""
@app.route("/mark_unsafe", methods=["POST"])
def mark_unsafe():
	incidence = Incidence.query.filter_by(id=request.form['incidence_id']).first()
	current_user.unmark(incidence)
	db.session.commit()
	"""Returning jsonify does nothing much, 
	we just use it to stop the server from throwing an error."""
	return jsonify({'success':'true'})

"""This routes is used to add a new incidence asynchronouly to the
database.
By recieving form data from JQuery containing name, location, and author"""
@app.route('/add_incidence', methods=['POST'])
def add_incidence():
	new_incidence = Incidence(name=request.form['name'],\
		location=request.form['location'], author=current_user)
	"""Here we just query all the users, 
	then add a notification for all of them"""
	all_user = User.query.all()
	for users in all_user:
		new_notify = Notifications(carrier_name=current_user.name,\
			carrier_id=current_user.id,\
			reciever_id=users.id,\
			action_type="incidence")
		db.session.add(new_notify)
		db.session.commit()
	db.session.add(new_incidence)
	db.session.commit()
	return jsonify({'successs':'true'})

"""This route is only served to admins, 
it helps them suspend accounts by setting 
the user account_pend to True"""
@app.route('/suspend_user', methods=['POST'])
def suspend_user():
	user = User.query.get_or_404(request.form['user_id'])
	user.account_pend = True
	db.session.commit()
	return jsonify({'successs':'true'})

"""This route is only served to admins, 
it helps them relieve suspended accounts by setting 
the user account_pend to False"""
@app.route('/relieve_user', methods=['POST'])
def relieve_user():
	user = User.query.get_or_404(request.form['user_id'])
	user.account_pend = False
	db.session.commit()
	return jsonify({'successs':'true'})

"""This route gets the form data sent by JQuery,
 then uses it to update the users profile"""
@app.route('/update_profile', methods=['POST'])
def update_profile():
	current_user.name = request.form['name']
	current_user.number = request.form['number']
	current_user.location = request.form['location']
	db.session.commit()
	return jsonify({'success':'true'})

"""This save_picture function takes an argument,
which is an image data"""
def save_picture(form_picture):
	"""Here we use the secrets module to generate a random
	name, and assign it to a variable called new_name"""
	new_name = secrets.token_hex(8)
	"""In this section, we are getting the filename
	and the file extension using the os.path.splittext
	it returns a list of two value, which contains the 
	filename and the file_extension. The _ variable is a throw
	away variable, the main one is the f_ext which contains
	 the file_extension"""
	_, f_ext = os.path.splitext(form_picture.filename)
	"""The picture_fn is a new variable that was generated by merging the 
	new_name variable and the f_ext variable"""
	picture_fn = new_name + f_ext
	"""Now we use os.path.join the merge the application root path,
	with the static/img folder and also the picture_fn"""
	picture_path = os.path.join(app.root_path, 'static/img', picture_fn)
	"""We are using the Image module we imported from PIllow Library to open and save the image
	to the picture_path"""
	i = Image.open(form_picture)
	i.save(picture_path)
	#lastly we return the picture file name, which we will insert to the database
	return picture_fn

"""This routes updates the user photo asynchronously, by
recieving image data from Jquery, then calls the save_picture()
function and passes the file to it."""
@app.route("/update_photo",  methods=['POST'])
def update_photo():
	"""Here we pass the gotten image to the save_picture function, then 
	it returns the filename and the file name is assigned to
	 the picture_file variable"""
	picture_file = save_picture(request.files.get('file'))
	"""now we assign the picture_file to the current_user.profile_image, then
	we commit it to the database"""
	current_user.profile_image = picture_file
	db.session.commit()

	return jsonify({'success' : 'true', 'like_num' : 3})

"""This remove_photo route doesnt recieve anything from JQuery.
it just turns the current_user profile image back to the default
image"""
@app.route("/remove_photo",  methods=['POST'])
def remove_photo():
	"""Here we are setting the current_user 
	profile image to default.jpg"""
	current_user.profile_image = "default.jpg"
	db.session.commit()
	"""We are returning this JSonify that the server will not throw an error."""
	return jsonify({'success' : 'true', 'like_num' : 3})

"""This route is asynchronously recieving form data sent by JQuery.
The data recieved is the incidence id and the comment body"""
@app.route("/add_comment", methods=['POST'])
def add_comment():
	"""Here, we are querying the incident database, using the incidence
	id we recieved from JQUery."""
	incidence = Incidence.query.get_or_404(request.form['id'])
	"""Here we are adding the comments to the database and commiting it"""
	new_comment = Comment(comm_ent=current_user, commenter=incidence,\
		body=request.form['body'])
	db.session.add(new_comment)
	db.session.commit()
	"""The only usefulness of returning this JSonify is just so that the
	server will not throw an error."""
	return jsonify({'success':'true'})


""" This is where the service worker file is beign
served """
@app.route('/service-worker.js')
def sw():
	return app.send_static_file('service-worker.js'), 200, {'Content-Type': 'text/javascript'}


"""This file is not meant to be tampered with
it helps the website function like an application"""
@app.route('/.well-known/assetlinks.json')
def assets():
	return app.send_static_file('assetlinks.json')