/* © SRSoftware 2025 */
package de.srsoftware.umbrella.web;

import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.WARNING;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;

import com.sun.net.httpserver.HttpExchange;
import de.srsoftware.tools.Path;
import de.srsoftware.umbrella.core.BaseHandler;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class WebHandler extends BaseHandler {

	public WebHandler(){
		super();
	}

	@Override
	public boolean doGet(Path path, HttpExchange ex) throws IOException {
		LOG.log(DEBUG,"doGet({0},ex)",path);

		// legacy download links: redirect to new api
		if ("files/download".equals(path.toString())) {
			var file = queryParam(ex).get("file");
			var target = "/api/files/"+file;
			return sendRedirect(ex,target);
		}

		// we always need to load the index.html first, when we encounter something like /module/entry/4/view
		// the index page itself references required elements with absolute path: /assets/index-x.js
		var first = path.isEmpty() ? null : path.firstElement();
		if (first == null || !first.contains(".")){
			path.clear();
			path.push("index.html");
		}
		var url = getClass().getClassLoader().getResource("web/"+path);
		if (url == null) return sendContent(ex,404,path+" not found!");
		LOG.log(DEBUG,"Trying to load {0}",url);
		var bos = new ByteArrayOutputStream();
		var conn = url.openConnection();
		var mime = conn.getContentType();
		try (var stream = conn.getInputStream()){
			stream.transferTo(bos);
			ex.getResponseHeaders().add(CONTENT_TYPE,mime);
			return sendContent(addCors(ex),bos.toByteArray());
		} catch (Exception e) {
			LOG.log(WARNING,"Failed to load {0}",url);
			return sendContent(ex,HTTP_NOT_FOUND,"Failed to load "+url);
		}
	}
}
