const http = require("http");
const  url = require("url");
const   fs = require("fs");

let contents = "";
let nextID = 101;
let people = [{name: "Homer", id:nextID++, age: 26, photo:"/images/homer.jpg", messages:[]},
			  {name: "Marge", id:nextID++, age: 25, photo:"/images/marge.jpg", messages:[]},
			  {name: "Ling", id:nextID++, age: 27, photo:"/images/ling.jpg", messages:[]},
			  {name: "Ahmed", id:nextID++, age: 24, photo:"/images/ahmed.jpg", messages:[]}];
let anonImg = "/images/unknown_person.jpg";

// Helper function for sending 404 message
function send404(response) {
	response.writeHead(404, {"Content-Type": "text/plain"});
	response.write("Error 404: Resource not found.");
	response.end();
}

// Helper function for sending back the main homepage
function respondMainPage(res) {
  contents = `
    <!DOCTYPE html>
	<html>
      <head>
        <title>Date-a-Science</title>
        <link rel="stylesheet" href="/style.css">
		<link rel="icon" href="/images/favicon.jpg" type="image/jpeg">
      </head>
      <body>
	  	<nav class="navbar">
    		<div class="nav-left">
      			<img src="/images/logo.jpg" alt="Logo" class="logo">
      			<span class="site-title">Date-a-Science</span>
    		</div>
   			 <ul class="nav-menu">
      			<li><a href="/">Home</a></li>
      			<li><a href="/about">About</a></li>
    		</ul>
  		</nav>
		<div class="banner">
    		<img src="/images/loveBanner.jpg" alt="Love Banner">
  		</div>
        <div class="container">
          <h1>Welcome to Date-a-Science</h1>
          <p>Where Your Heart Gets a Software Update.</p>

          <h2>Our Members</h2>
          <ul class="profile-list">
  `;

  people.forEach(person => {
    contents += `<li><a href="./profile?id=${person.id}">&#x2665; ${person.name}</a></li>`;
  });

  contents += `
          </ul>

          <h2>Create a New Profile</h2>
          <label for="name">Name:</label>
          <input type="textbox" id="name"> 
          <button type="button" onclick="submit()">Submit Profile</button>

          <script src="/clientscript.js"></script>
        </div>

		<footer>
      		<p>&copy; 2025 Date-a-Science</p>
      		<p>Contact us at <a href="mailto:support@dateascience.com">support@dateascience.com</a></p>
   		 </footer>

      </body>
    </html>
  `;

  res.writeHead(200, { "Content-Type": "text/html" });
  res.end(contents);
}


// Helper function for sending back the profile page
function respondWithProfile(res, id) {
	// This is not an efficient way of finding people. You may want to use a HashMap.
	let person = null;
	for (let i=0; i<people.length; i++) {
		if (people[i].id == id) {
			person = people[i];
			break;
		}
	}
	// If the person is not found, send back an error
	if (person === null) {
		send404(res);
		return;
	}
	
	const photo = person.photo || anonImg;
  	contents = `
    	<!DOCTYPE html>
		<html>
      		<head>
        		<title>${person.name} - Date-a-Science</title>
        		<link rel="stylesheet" href="/style.css">
				<link rel="icon" href="/images/favicon.jpg" type="image/jpeg">
      		</head>
      		<body>
        		<div class="container">
          			<a href="/" class="back-link">< Back to homepage</a>

          			<div class="profile-card">
            			<h1>${person.name}</h1>
            			<img src="${photo}" width="200" alt="${person.name}'s photo">
            			<p><strong>Age:</strong> ${person.age}</p>
          			</div>

          			<div class="messages">
            			<h2>Messages</h2>`;
                        if (person.messages.length !== 0) {
                            person.messages.forEach(msg => {
			                    contents += `<div class="message">${msg}</div>`;
		                    });
	                    } else {
		                    contents += `<p>No messages yet.</p>`;
	                    }
            		    contents += `<h3>Leave a Message</h3>
            			<input type="textbox" id="msg">
            			<button type="button" onclick="submitMessage(${person.id})">Submit Message</button>
          			</div>

          			<script src="/clientscript.js"></script>
        		</div>
      		</body>
    	</html>
  	`;
  	res.writeHead(200, { "Content-Type": "text/html" });
  	res.end(contents);
}


// Return the MIME type given the filename
function lookupMIMEType(filename) { 
	if (filename.endsWith(".js")) return "application/javascript";
	if (filename.endsWith(".css")) return "text/css";
	if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) return "image/jpeg";
	if (filename.endsWith(".png")) return "image/png";
	if (filename.endsWith(".html")) return "text/html";
	return "text/plain";
}

// Send back the specific file requested (html, JavaScript, css, jpg, or plain text)
function serveStaticFile(filename, res) {
	fs.readFile(filename, function(err, data) {
		if (err) {
			res.statusCode = 404;
			res.end("File not found");
		} else {
		    res.writeHead(200, {"content-type": lookupMIMEType(filename)});
		    res.end(data);
        }
	});
}

// Helper function to read the request body
function readRequestBody(req, callback) {
	let body = ""
	req.on("data", (chunk) => {
		body += chunk;
	})
	//Once the entire body is ready, process the request
	req.on("end", () => {
		callback(body);
	});
}

// Helper function to add a message to a person's profile
function addMessage(msg) {
	for (let i=0; i<people.length; i++) {
		if (people[i].id === msg.id) {
			people[i].messages.push(msg.message); // add it
			return true;
		}
	}
	return false;
}

// Listener for incoming client requests
function handleRequest(req, res) {
	const parsed = url.parse(req.url, true); // get the query params (for profile pages)
	const pathname = parsed.pathname;        // get path without query

	// Handle all GET requests
	if (req.method === "GET") {
		if (pathname === "/" || pathname === "/home") {// Return the main page
			respondMainPage(res);
		} else if (pathname.startsWith("/profile")) { // Return a specific profile
			respondWithProfile(res, parsed.query.id);
		} else if (pathname.startsWith("/about")) {    // Return the about page
			serveStaticFile("./about.html", res);
		} else if (pathname === "/clientscript.js") {  // Return the client-side javascript
			serveStaticFile("./clientscript.js", res);
		} else if (pathname.startsWith("/images/")) {  // Return an image for a page
			serveStaticFile("." + pathname, res);
		} else if (pathname === "/style.css") {        // Return the style file
  			serveStaticFile("./style.css", res);
		} else { // If anything else ... respond with 404 error
			send404(res);
		}
	} 
	// Combination of PUT and /newprofile is interpreted as a request to create a profile
	else if (req.method === "PUT" && pathname === "/newprofile") {
		readRequestBody(req, function(body) {
			newPerson = JSON.parse(body);
			newPerson.id = nextID++;
			newPerson.messages = [];
			people.push(newPerson); // add profile to the array
			res.writeHead(200, { "content-type": "text/plain" });
			res.end();
		});
	// Combination of POST and /message is interpreted as a request to add a message
	} else if (req.method === "POST" && pathname === "/message") {
		readRequestBody(req, function(body) {
			console.log("Adding message: " + body);
			let message = JSON.parse(body);
			if (addMessage(message)) {
				res.writeHead(200, { "content-type": "text/plain" });
				res.end();
			} else {
				send404(res);
			}
		});
	//Any other combination of method/URL is not supported
	} else { // If no matches, send 405
		res.writeHead(405);
		res.end("Unsupported method");
	}
}

http.createServer(handleRequest).listen(3000);
console.log("Server running on port 3000");