from flask import Flask
from flask import Response, jsonify, request, redirect, url_for
from flask import send_from_directory

import socket
import os, re
from werkzeug.utils import secure_filename

#import pipeline
from pipeline import backend

#mac-specific relative path to the script's location
UPLOAD_FOLDER = './sqlite'
ALLOWED_EXTENSIONS = set(['.db'])

#configuration
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


@app.route('/', methods=['GET', 'POST'])
def upload_file():

    print 'uploading provided file'
    
    try:
        os.stat(app.config['UPLOAD_FOLDER'])
    except:
        os.mkdir(app.config['UPLOAD_FOLDER'])

    if request.method == 'POST':
        if request.files.has_key('chrome'):
            chrome = request.files['chrome']
            if chrome:
                filename = secure_filename(chrome.filename)
                print 'we got a file called ', filename
                chrome.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                return redirect(url_for('uploaded_file',filename=filename))

    return open('templates/upload_file.html').read()

    

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    print filename, 'my file name'
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)


@app.route('/analyzing',methods=['POST', 'GET'])
def analyze_page():

    chromedbpath=UPLOAD_FOLDER+'/'+ 'chromeDB.db'
    return backend(chromedbpath)


if __name__ == '__main__':

    print(socket.gethostbyname(socket.gethostname()))
    app.run(host='0.0.0.0', port=80, debug=True)