import os
import torch
import socket
import time
from flask import Flask,url_for,request,render_template,redirect,jsonify,send_from_directory
from datetime import datetime
from flask_jsglue import JSGlue
from torch import Tensor
from model.model import Run,deal_pairs,deal_select
app=Flask(__name__,template_folder="./templates",static_folder="./static")
app.jinja_env.auto_reload=True
app.config['TEMPLATES_AUTO_RELOAD']=True
jsglue=JSGlue(app)
@app.route('/upload',methods=['POST'])
def upload():
	if request.method=='POST':
		f=request.files['file']
		ip=request.remote_addr
		basepath=os.path.dirname(__file__)
		common_path=os.path.join(basepath,'uploads/')
		file_name=str(round(time.time()*1000))
		dir=str(time.strftime('%y%m%d', time.localtime()))
		upload_path=common_path+dir
		if not os.path.exists(upload_path):
			os.mkdir(upload_path)
		file_path = str(file_name)+str(f.filename)
		PATH=upload_path+"/"+file_path
		f.save(PATH)
		f.close()
		with open(PATH,'r',encoding='UTF-8') as f:
			lines=f.readlines()
			for line in lines:
				if line.strip().startswith("//"):
					continue
				Type=line[0]
				break
			Genes=[]
			Gene_dic={}
			for line in lines:
				if line.strip().startswith("//"):
					continue
				sp=line.split()
				if len(sp)==1:
					Genes.append(sp[0])
					Gene_dic[sp[0]]=[]
				else:
					sp=[float(i) for i in sp]
					if sum(sp)>0:
						Gene_dic[Genes[-1]].append(sp)
		for gene in Genes:
			if len(Gene_dic[gene])==0:
				Genes.remove(gene)
				Gene_dic.pop(gene)
		Pairs=[]
		if Type=="1":
			for i in range(len(Genes)):
				for j in range(i+1,len(Genes)):
					Pairs.append((Genes[i],Genes[j]))
		elif Type=="2":
			for i in range(0,len(Genes),2):
				Pairs.append((Genes[i],Genes[i+1]))
		PAIR_PATH=deal_pairs(Pairs,Gene_dic)
		
		loader=torch.load(PAIR_PATH)
		Results=Run(loader)
		outputs="Most likely possible fusion pairs:\n"
		for each in Results:
			g0=each[1]
			g1=each[2]
			val=(Tensor.cpu(each[0]).item())
			outputs+=each[1]+"\t"+each[2]+"\t"+str(val)+"\n"
		PATH=PAIR_PATH[:-4]+'_result.txt'
		with open(PATH,'w',encoding='UTF-8') as f:
			f.write(outputs)
		return jsonify({'outputs':outputs,'PATH':PATH})
@app.route('/load',methods=['GET'])
def load():
	FILE=request.args['file']
	try:
		with open(FILE,'r',encoding='UTF-8') as f:
			data=f.read()
		return data
	except:
		return ""
@app.route('/select',methods=['GET'])
def select():
	FILE=request.args['file']
	the=request.args['the']
	return deal_select(FILE,the)
@app.route('/')
def index():
	return render_template('index.html')

@app.route('/download/<filename>', methods=['GET'])
def download(filename):
    if request.method == "GET":
        path = os.path.isfile(os.path.join('files/', filename));
        if path:
            return send_from_directory('files/', filename, as_attachment=True)
if __name__ == "__main__":
	app.run()
