#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import json
#from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from http.server import BaseHTTPRequestHandler
import os
from utils.utils import get_list_overlays, load_config, write_config, sort_install_pkg
from utils.package import search
from utils.findfsdb import on_find 
from src.route import Router
from io import BytesIO
#repl = '<?xml version=\'1.0\' encoding=\'utf-8\'?>\n<!DOCTYPE repositories SYSTEM "http://www.gentoo.org/dtd/repositories.dtd">'
class Handler(BaseHTTPRequestHandler):
	def get_data(self):
		#length = int(self.headers['content-length'])
		#self.setHeader['Access-Control-Allow-Origin', '*']
		#self.headers['Access-Control-Allow-Methods', 'GET']
		#self.headers['Access-Control-Allow-Headers', 'X-Requested-With,content-type']
		#self.headers['Access-Control-Allow-Credentials', true]
		length = int(self.headers['content-length'])
		data = self.rfile.read(length)
		return(str(data))

	def r_403(self):
		self.send_response(403)
		self.end_headers()
		print(self.client_address)
	
	def r_404(self):
		self.send_response(404)
		self.end_headers()
		print(self.client_address)

	def route(self):
		if self.path in route:
			return true
		else:
			return false

	def parse_url(self):
		pass

	def do_GET(self):
    #length = int(self.headers['content-length'])
		#self.headers['Access-Control-Allow-Origin', '*']
		#self.headers['Access-Control-Allow-Methods', 'GET']
		#self.headers['Access-Control-Allow-Headers', 'X-Requested-With,content-type']
		#self.headers['Access-Control-Allow-Credentials', true]
		self.r_t =""
		#print(Router.parse_url(self))
		#print("data:\t" + self.rfile.read())
		#request = Router.parse_url(self)
		self.send_response(200)
		self.end_headers()
		if self.path =="/":
			#print("data:\t" + self.get_data())
			"""
			with open('./views/index.html', 'tr') as f: 
				self.r_t=f.read()
			print(self.client_address)
			"""
			try:
				with open('./pkgs.json', 'tr') as fn:
					data = fn.read()
					pkg_list = json.loads(data)
					print(pkg_list)
			except Exception(e):
				print(e)
			self.r_t = json.dumps(pkg_list)
		elif self.path  == '/main':
			#print(self.rfile.read())
			with open("./README.txt", 'r') as f:
				self.r_t = str(f.read())
				#self.r_t = s
		elif self.path == '/ovelays':
			overlays = get_list_overlays()
			#print(ovls)
			if overlays:                  #			== "":
				overlays ="Error"

			self.r_t=json.dumps({"repositories": overlays})
			
		elif self.path == "":
			with open('./favicon.png', 'rb') as f:
				self.r_t = f.read()
				
		elif self.path == '/logo.png':
			pass

		elif self.path.startswith( "/static/"):
			self.r_static()
			self.send_response(200)
			#print(self.r_t)
		elif self.path == '/get_dump_list':
			try:
				with open('./pkgs.json', 'tr') as fn:
					data = fn.read()
					pkg_list = json.loads(data)
					print(pkg_list)
			except Exception (e):
				print(str(e))
			self.r_t = json.dumps({"dump_portage": pkg_list})

		elif self.path.startswith("/?st_app="):
			config = load_config()
			param = self.path.replace("/?st_app=", "") 
			list_param = param.split(',')
			print(list_param)
			for i in list_param:
				if i.startswith('port'):
					port = int(i.split('=')[1])	
				elif i.startswith('Lang'):
					Lang = i.split('=')[1]
				
			write_config(port, Lang)
			print(config)
			print(param)

		elif self.path.startswith("/find?pkg="):
			param = self.path.replace("/find?pkg=", "")  #request['params']['name']
			pk_list = []
			search_result = {}
			if len(param.split('/')) == 2:
				param = param.split('/')[1]
			p_list = on_find(param)
			print(p_list)
			if len(p_list) == 0:
				print("Never Found")
				self.r_t = str(json.dumps({"Package_result": p_list}))
			else:
				for p in p_list:
					print(p)
			if len(param.split("/")) == 2:
				pk_list.append(search(param.split("/")[1]))
			else:
				pk_list.append(search(param))
				#print(pk)
			search_result = {"Package_result": pk_list}
			self.r_t = str(json.dumps(search_result))

		elif self.path == "get_settings_app":

			self.r_t = str(json.dumps(load_config()))

		elif self.path == 'get_portage':

			#self.r_t = str(sort_inatll_pkg())
			self.r_t = str(json.dumps(scan_config_portage()))
        
		elif '.py?' in self.path:
			print("loading")
			self.path = str(self.path.split('?')[0])
			print(self.path)
			self.r_static()
        
		else:
			self.send_response(404)
			
			self.end_headers()
			print(str(self.client_address[0]) +"\t" + str(404))

        # Send the html message
		#self.wfile.write(bytes(self.r_t, "utf-8"))
		try:
			return self.wfile.write(BytesIO(self.r_t).getvalue())
		except TypeError:
			#print("TypeError")
			return self.wfile.write(bytes(self.r_t, 'UTF-8'))

	def r_static(self):
		if os.path.exists('./views/' + self.path):
			self.send_response(200)
			self.end_headers()
			with open('./views/' + self.path, 'tr') as f:
				self.r_t=f.read()
			
		else:
			self.send_response(404)
			self.end_headers()
