from flask import Flask, request, url_for, render_template, jsonify
from flask_api import FlaskAPI, status, exceptions
import subprocess
import yaml
from werkzeug.utils import secure_filename
import codecs
import json
import time

app = Flask(__name__)
ALLOWED_EXTENSIONS = set(['txt', 'pdf'])


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


def translate(text):
    start_time = time.time()
    """
    Run translation model using config
    """
    with open("/home/tugasakhir/run/config.yaml", 'r') as f:
        doc = yaml.safe_load(f)
    fileIn = doc['sample-models']['in']
    fileOut = doc['sample-models']['out']
    homeDir = doc['sample-models']['homeDir']
    runCommand = doc['sample-models']['command']
    status = 'Files successfully read'
    subprocess.call(['rm %s && rm %s' % (fileIn, fileOut)], shell=True)
    text8 = text
    inputFile = open(fileIn, 'w')
    inputFile.write(text8 + '\n')
    inputFile.close()
    subprocess.call([runCommand], cwd=homeDir, shell=True)
    readTranslate = open(fileOut, 'r')
    translatedText = readTranslate.read()
    readTranslate.close()
    ##return {
            ##"STATUS": status,
            ##"LAN": 'N/A',
            ##"MODEL": str(homeDir),
            ##"CMD": str(runCommand),
            ##"URL": request.host_url.rstrip('/'),
            ##"INPUT": text,
            ##"INPUT_SIZE": len(text),
            ##"INPUT_PATH": str(fileIn),            
            ##"OUTPUT": translatedText.rstrip(),
            ##"OUTPUT_SIZE": len(translatedText),
            ##"OUTPUT_PATH": str(fileOut),
            ##"DURATION": '%.3f seconds' % (time.time() - start_time)
    ##}
    result = {
        "output": translatedText.rstrip()
    }
    result = {str(key): value for key, value in result.items()}
    return jsonify(result=result)

@app.route('/hello/', methods=['GET', 'POST'])
def home():
    return render_template('home.html')

@app.route("/", methods=['GET'])
def instructions():
    return render_template('home.html')


@app.route("/<text>", methods=['GET'])
def user_get(text):
    """
    Translate text
    """
    text = translate(text)
    return text

@app.route("/trans", methods=['GET', 'POST'])
def trans_word():
    text = request.form['text']
    text = translate(text)
    return text

@app.route("/upload", methods=['POST', 'PUT'])
def upload():
    """
    Tranlsate file
    """
    file = request.files['name']
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        text = file.read()
        text = translate(text)
        return text
    else:
        return ('Error reading file...\n')
