from flask import Flask, send_file, request
from time import sleep
from werkzeug.serving import make_server
from threading import Thread
from mysql.connector import connect, Error
from macros import *
import os, json, config, requests, logging
class WSThread(Thread):
	app = Flask(__name__)
	conn = None
	def __init__(self, event):
		super(WSThread, self).__init__()
		self.event = event
		log = logging.getLogger('werkzeug')
		log.disabled = True
	@app.route('/')
	@app.route('/index')
	def index():
		return ''
	@app.route('/index.js')
	def indexjs():
		return send_file('index.js')
	@app.route('/curstatus.json')
	def curstatus():
		j = {}
		j['info'] = {}
		j['info']['asics'] = {}
		return json.dumps(j), 200, {'ContentType':'application/json'}
	def dbinit(self):
		with self.conn.cursor() as c:
			c.execute("""
				CREATE TABLE IF NOT EXISTS `ips` (
					`id` INT AUTO_INCREMENT PRIMARY KEY,
					`ip` VARCHAR(64) NOT NULL,
					`location` VARCHAR(64) NOT NULL
				)
			""")
			c.execute("""
				CREATE TABLE IF NOT EXISTS `laststate` (
					`id` INT AUTO_INCREMENT PRIMARY KEY,
					`ip` VARCHAR(64) NOT NULL,
					`mac` VARCHAR(32) NOT NULL,
					`type` INT(11) NOT NULL,
					`location` VARCHAR(64) NOT NULL,
					`status` VARCHAR(32) NOT NULL,
					`time` INT(11) NOT NULL
				)
			""")
			c.execute("""
				CREATE TABLE IF NOT EXISTS `asiclogs` (
					`id` INT AUTO_INCREMENT PRIMARY KEY,
					`ip` VARCHAR(64) NOT NULL,
					`mac` VARCHAR(64) NOT NULL,
					`type` VARCHAR(64) NOT NULL,
					`time` INT(11) NOT NULL,
					`log` TEXT NOT NULL
				)
			""")
			self.conn.commit()
	def runweb(self):
		self.server = make_server('0.0.0.0', CONF.get('port'), self.app)
		self.server.serve_forever()
	def run(self):
		try:
			with connect(host=CONF.get('db', 'host'), user=CONF.get('db', 'user'), password=CONF.get('db', 'password')) as conn:
				with conn.cursor() as c:
					c.execute(f"CREATE DATABASE IF NOT EXISTS {CONF.get('db', 'name')}")
			self.conn = connect(
				host=CONF.get('db', 'host'),
				user=CONF.get('db', 'user'),
				password=CONF.get('db', 'password'),
				database=CONF.get('db', 'name'))
			self.dbinit()
			web = Thread(target=self.runweb)
			web.daemon = True
			web.start()
			SUCC(f"Web interface started at port {CONF.get('port')}!")
			while not self.event.is_set():
				sleep(1)
			SUCC(f"Web server stopped!")
			self.server.shutdown()
		except Exception as e:
			CRIT(str(e))
			os._exit(1)