import os

from flask_restful import Resource, Api
from flask import Flask, render_template, request, jsonify, redirect, url_for, send_from_directory
from werkzeug.utils import secure_filename
from MailSender import send
from flask_triangle import Triangle
from pymongo import MongoClient
import Matcher
import json
import ruamel.yaml as yaml


from os import listdir

from SkillExtractor import pdf_to_text, process_resume, pdf_to_sentences
app = Flask(__name__)
Triangle(app)
api = Api(app)
app.config['UPLOAD_FOLDER'] = 'resumes-pdf'
app.config['CV_UPLOAD_FOLDER'] = 'cv-uploads'
app.config['UPLOADJD_FOLDER'] = 'C:\Users\Shekar_Gadamoni\Desktop\pyders-hackathon\src\jds'
ALLOWED_EXTENSIONS = set(['pdf'])

client = MongoClient()
hackathon = client.hackathon



def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


@app.route('/', methods=['GET', 'POST'])
def index():
    return send_from_directory("static/", "index.html")


@app.route('/schedule', methods=['GET'])
def schedule():
    recipient = request.args.get("email")
    return send_from_directory("static/pages/", "schedule.html")


@app.route('/upload', methods=['GET', 'POST'])
def uploader():
    if request.method == 'POST':
        file = request.files['file']
        candidate_name = request.form.get("username")
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            pdftotext = pdf_to_text(app.config['UPLOAD_FOLDER'] + "/" + filename)
            sentences = pdf_to_sentences(app.config['UPLOAD_FOLDER'] + "/" + filename)
            processed_text = process_resume(pdftotext, candidate_name, app.config['UPLOAD_FOLDER'] + "/", sentences)
            os.remove(app.config['UPLOAD_FOLDER'] + "/" + filename)
    return "OK"


@app.route('/cvupload', methods=['GET', 'POST'])
def cvuploader():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['CV_UPLOAD_FOLDER'], filename))
    return "OK"


@app.route('/bulk-upload', methods=['GET', 'POST'])
def bulk_uploader():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            pdftotext = pdf_to_text(app.config['UPLOAD_FOLDER'] + "/" + filename)
            processed_text = process_resume(pdftotext)
            print "Processed Resume"
            os.remove(app.config['UPLOAD_FOLDER'] + "/" + filename)
    return "OK"

@app.route('/uploadJD', methods=['GET','POST'])
def uploadJD():
    if request.method == 'POST':
        file = request.files['file']
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOADJD_FOLDER'], filename))
        insertToMongo(request.form['title'],request.form['Experience'],request.form['location'],filename)
        return redirect(url_for('index'))
    return "OK"


@app.route('/invite', methods=['GET'])
def invite():
    recipient = request.args.get("email")
    bodyPath = "C:\Users\Shivakumar_Kanneboin\Desktop\Pyders\pyders-hackathon\src\email_message.txt"
    subject = "EPAM Systems India Pvt. Ltd. "
    link = "http://localhost:2035/schedule?email="+recipient
    send(subject, bodyPath, recipient, link)



@app.route('/jdslist',methods=['GET','POST'])
def getListofJds():
    filepath= app.config['UPLOADJD_FOLDER']
    listOfJds = list()
    for record in hackathon.JdDb.find({}):
        listOfJds.append(record)
    resultlist = list()
    for dicts in listOfJds:
        dictf = dict()
        for i in dicts:
            dictf.__setitem__(str(i),str(dicts[i]))
            resultlist.append(dictf)
    return str(resultlist)


@app.route('/matchingProfiles', methods=['GET', 'POST'])
def matchingProfiles():
    # matcherObject = Matcher()
    result = hackathon.JdDb.find({"title": request.form["title"]})[0]
    # print(result['Description'])
    result = Matcher.matcher(result['Description'])
    print(result)
    return result.__str__()


def insertToMongo(title, Experience, location, filename):
    description = open(app.config['UPLOADJD_FOLDER'] + "\\" + filename, 'r').read()
    print (description)
    hackathon.JdDb.insert_one({
        "title": title,
        "Experience": Experience,
        "Location": location,
        "Description": description
    })


class Welcome(Resource):
    def get(self):
        data = {'name': 'Shiva Kumar', 'Company': 'EPAM Systems India Pvt. Ltd.', 'email': 'shiva2035.iiit@gmail.com',
                'mobile': 9963808956}
        return jsonify(data)

api.add_resource(Welcome, '/welcome')





if __name__ == '__main__':
    app.run(host='localhost', port=2035, debug=True)
