import http.server
import socketserver
import json
import os
import urllib.parse
import subprocess

PORT = 8000
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
FULL_DIR = os.path.join(SCRIPT_DIR, "..", "full")
THUMB_DIR = os.path.join(SCRIPT_DIR, "..", "thumbs")
KAT_FILE = os.path.join(SCRIPT_DIR, "kategoriak.json")
KEP_FILE = os.path.join(SCRIPT_DIR, "kepek.json")

class EditorHandler(http.server.SimpleHTTPRequestHandler):
    def log_message(self, format, *args):
        # Elnémítjuk a szerver logokat (pl. GET kérések), hogy ne szemetelje tele a konzolt
        pass

    def end_headers(self):
        self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate')
        self.send_header('Pragma', 'no-cache')
        self.send_header('Expires', '0')
        super().end_headers()

    def translate_path(self, path):
        parsed_path = urllib.parse.urlparse(path).path
        if parsed_path.startswith('/full/'):
            filename = urllib.parse.unquote(parsed_path.replace('/full/', ''))
            return os.path.join(FULL_DIR, filename)
        elif parsed_path.startswith('/thumbs/'):
            filename = urllib.parse.unquote(parsed_path.replace('/thumbs/', ''))
            return os.path.join(THUMB_DIR, filename)
        return super().translate_path(path)
        
    def do_GET(self):
        parsed_path = urllib.parse.urlparse(self.path).path
        
        if parsed_path == '/' or parsed_path == '/index.html':
            self.path = '/editor.html'
            return super().do_GET()
            
        elif parsed_path == '/api/data':
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            
            kategoriak = []
            if os.path.exists(KAT_FILE):
                with open(KAT_FILE, 'r', encoding='utf-8') as f:
                    kategoriak = json.load(f)
                    
            kepek = []
            if os.path.exists(KEP_FILE):
                with open(KEP_FILE, 'r', encoding='utf-8') as f:
                    kepek = json.load(f)
                    
            response = {'kategoriak': kategoriak, 'kepek': kepek}
            self.wfile.write(json.dumps(response).encode('utf-8'))
            return
            
        return super().do_GET()

    def do_POST(self):
        parsed_path = urllib.parse.urlparse(self.path).path
        
        if parsed_path == '/api/save':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            data = json.loads(post_data.decode('utf-8'))
            
            # 1. Törlendő fájlok fizikai eltávolítása
            for kep in data['kepek'][:]: # Másolatot készítünk az iteráláshoz
                if kep.get('kategoria') == -1:
                    filename = kep['fajlnev']
                    full_path = os.path.join(FULL_DIR, filename)
                    thumb_path = os.path.join(THUMB_DIR, f"tn_{filename}")
                    try:
                        if os.path.exists(full_path): os.remove(full_path)
                        if os.path.exists(thumb_path): os.remove(thumb_path)
                    except: pass
                    data['kepek'].remove(kep)

            with open(KAT_FILE, 'w', encoding='utf-8') as f:
                json.dump(data['kategoriak'], f, ensure_ascii=False, indent=4)
                
            with open(KEP_FILE, 'w', encoding='utf-8') as f:
                json.dump(data['kepek'], f, ensure_ascii=False, indent=4)
                
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps({"status": "ok"}).encode('utf-8'))
            return
            
        elif parsed_path == '/api/run_update':
            try:
                subprocess.run(["python", "update_gallery_db.py"], cwd=SCRIPT_DIR, check=True)
                self.send_response(200)
                self.end_headers()
                self.wfile.write(json.dumps({"status": "ok", "message": "Adatbázis frissítve!"}).encode('utf-8'))
            except Exception as e:
                self.send_response(500)
                self.end_headers()
                self.wfile.write(json.dumps({"status": "error", "message": str(e)}).encode('utf-8'))
            return
            
        elif parsed_path == '/api/run_generate':
            try:
                subprocess.run(["python", "generate_gallery.py"], cwd=SCRIPT_DIR, check=True)
                self.send_response(200)
                self.end_headers()
                self.wfile.write(json.dumps({"status": "ok", "message": "Weboldal legenerálva!"}).encode('utf-8'))
            except Exception as e:
                self.send_response(500)
                self.end_headers()
                self.wfile.write(json.dumps({"status": "error", "message": str(e)}).encode('utf-8'))
            return
            
        elif parsed_path == '/api/delete_file':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            data = json.loads(post_data.decode('utf-8'))
            filename = data.get('filename')
            
            if filename:
                full_path = os.path.join(FULL_DIR, filename)
                thumb_path = os.path.join(THUMB_DIR, f"tn_{filename}")
                
                try:
                    if os.path.exists(full_path):
                        os.remove(full_path)
                    if os.path.exists(thumb_path):
                        os.remove(thumb_path)
                        
                    self.send_response(200)
                    self.send_header('Content-type', 'application/json')
                    self.end_headers()
                    self.wfile.write(json.dumps({"status": "ok"}).encode('utf-8'))
                except Exception as e:
                    self.send_response(500)
                    self.end_headers()
                    self.wfile.write(json.dumps({"status": "error", "message": str(e)}).encode('utf-8'))
            else:
                self.send_response(400)
                self.end_headers()
            return

        self.send_response(404)
        self.end_headers()

def run(server_class=http.server.HTTPServer, handler_class=EditorHandler):
    os.chdir(SCRIPT_DIR) # Ensure we are in the data directory
    server_address = ('', PORT)
    httpd = server_class(server_address, handler_class)
    print(f"==================================================")
    print(f" VIZUÁLIS GALÉRIA SZERKESZTŐ SZERVER ELINDULT!")
    print(f" Nyisd meg a böngésződben ezt a címet:")
    print(f" http://localhost:{PORT}")
    print(f" A leállításhoz nyomj CTRL+C -t ebben az ablakban.")
    print(f"==================================================")
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print("Szerver leállítva.")

if __name__ == '__main__':
    run()
