from flask import Flask
from flask import Blueprint,render_template,request,url_for
from werkzeug.utils	import redirect
import os
from chfi.models import	Sensor
from datetime import datetime
import hashlib

bp = Blueprint('forensic', __name__, url_prefix='/forensic')

def	calculate_hash_string(text,	algorithm="md5"):
	"""문자열 해시 계산"""
	h =	hashlib.new(algorithm)
	h.update(text.encode("utf-8")) #1 : c4ca4238a0b923820dcc509a6f75849b(32자)
	return h.hexdigest()

def	calculate_hash_file(file, algorithm="md5"):
	"""파일 해시 계산	(chunk 단위로)"""
	h =	hashlib.new(algorithm)
	while chunk	:= file.read(8192):
		h.update(chunk)
	file.seek(0)  #	파일 포인터 초기화 (다시 사용 가능하도록)
	return h.hexdigest()


@bp.route('/',methods=["GET","POST"])
def	index():
	convert_result = ""
	active_tab = "home"	 # 기본값은	해시 탭
	
	if request.method == "POST":
		active_tab = request.form.get("active_tab",	"home")	 # 탭 정보	가져오기
		
		if active_tab == "home":
			option = request.form.get("convert_select")	 # string or file

			if option == "string":
				input_text = request.form.get("inputText", "")
				if input_text:
					result = calculate_hash_string(input_text)
					return render_template('forensic/index.html',convert_text=input_text,convert_result=result,active_tab=active_tab)
			elif option	== "file":
				uploaded_file =	request.files.get("inputFile")
				if uploaded_file and uploaded_file.filename	!= "":
					result = calculate_hash_file(uploaded_file)
					return render_template('forensic/index.html',convert_text=uploaded_file.filename,convert_result=result,active_tab=active_tab)
		elif active_tab	== "menu1":
			convert_result = "메타정보"

		elif active_tab	== "menu2":
			convert_result = "암호"

		elif active_tab	== "menu3":
			convert_result = "레지스트리"


	return render_template("forensic/index.html", convert_result=convert_result,active_tab=active_tab)
		
	
	
	

