package main import ( "database/sql" "encoding/json" "fmt" "io" "log" "net/http" "os" "path/filepath" "strings" ) func createSimulation(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") if r.Method == "OPTIONS" { w.Header().Set("Access-Control-Allow-Methods", "POST") w.WriteHeader(http.StatusOK) return } if r.Method != "POST" { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } bodyBytes, err := io.ReadAll(r.Body) if err != nil { http.Error(w, "Failed to read request body", http.StatusBadRequest) return } defer r.Body.Close() configStr := string(bodyBytes) if configStr == "" { http.Error(w, "Config cannot be empty", http.StatusBadRequest) return } // Check if this config already exists var existingID int var existingName string err = db.QueryRow("SELECT id, name FROM simulations WHERE config = ?", configStr).Scan(&existingID, &existingName) if err == nil { // Found exact config, return the existing run info w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]interface{}{ "id": existingID, "name": existingName, }) return } var count int db.QueryRow("SELECT COUNT(*) FROM simulations").Scan(&count) newName := fmt.Sprintf("simulation_%d", count+1) // ensure name doesn't exist for { var temp int err := db.QueryRow("SELECT id FROM simulations WHERE name = ?", newName).Scan(&temp) if err == sql.ErrNoRows { break } count++ newName = fmt.Sprintf("simulation_%d", count+1) } res, err := db.Exec("INSERT INTO simulations(name, config) VALUES(?, ?)", newName, configStr) if err != nil { log.Println("Insert simulation error:", err) http.Error(w, "Failed to create", http.StatusInternalServerError) return } newID, _ := res.LastInsertId() // Ensure the directory exists resultsDir := filepath.Join("../results", newName) os.MkdirAll(resultsDir, 0755) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]interface{}{ "id": newID, "name": newName, }) } func getSimulations(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") if r.Method == "OPTIONS" { w.Header().Set("Access-Control-Allow-Methods", "GET") w.WriteHeader(http.StatusOK) return } rows, err := db.Query("SELECT id, name, config, created_at, search_time, total_time FROM simulations") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer rows.Close() var sims []Simulation for rows.Next() { var s Simulation err = rows.Scan(&s.ID, &s.Name, &s.Config, &s.CreatedAt, &s.SearchTime, &s.TotalTime) if err != nil { log.Println("Row scan error:", err) continue } sims = append(sims, s) } if sims == nil { sims = []Simulation{} } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(sims) } func getSimulationDetails(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") if r.Method == "OPTIONS" { w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS") w.WriteHeader(http.StatusOK) return } pathParts := strings.Split(strings.Trim(r.URL.Path[len("/api/simulations/"):], "/"), "/") idStr := pathParts[0] if idStr == "" || idStr == "create" { http.Error(w, "Not found", http.StatusNotFound) return } if r.Method == "PUT" && len(pathParts) > 1 && pathParts[1] == "time" { updateSimulationTime(w, r, idStr) return } if r.Method == "POST" && len(pathParts) > 1 && pathParts[1] == "upload" { uploadSimulationResource(w, r, idStr) return } if r.Method != "GET" { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } var s Simulation err := db.QueryRow("SELECT id, name, config, created_at, search_time, total_time FROM simulations WHERE id = ?", idStr).Scan(&s.ID, &s.Name, &s.Config, &s.CreatedAt, &s.SearchTime, &s.TotalTime) if err != nil { if err == sql.ErrNoRows { http.Error(w, "Simulation not found", http.StatusNotFound) } else { http.Error(w, err.Error(), http.StatusInternalServerError) } return } rows, err := db.Query("SELECT filename FROM resources WHERE simulation_id = ?", s.ID) if err == nil { defer rows.Close() for rows.Next() { var fname string if err := rows.Scan(&fname); err == nil { s.Resources = append(s.Resources, fname) } } } if s.Resources == nil { s.Resources = []string{} } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(s) } func updateSimulationTime(w http.ResponseWriter, r *http.Request, idStr string) { var reqBody struct { SearchTime *float64 `json:"search_time"` TotalTime *float64 `json:"total_time"` } err := json.NewDecoder(r.Body).Decode(&reqBody) if err != nil { http.Error(w, "Invalid request body", http.StatusBadRequest) return } defer r.Body.Close() if reqBody.SearchTime == nil || reqBody.TotalTime == nil { http.Error(w, "Missing search_time or total_time", http.StatusBadRequest) return } _, err = db.Exec("UPDATE simulations SET search_time = ?, total_time = ? WHERE id = ?", *reqBody.SearchTime, *reqBody.TotalTime, idStr) if err != nil { log.Println("Update simulation error:", err) http.Error(w, "Failed to update", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{"status": "success"}) } func uploadSimulationResource(w http.ResponseWriter, r *http.Request, idStr string) { var simName string err := db.QueryRow("SELECT name FROM simulations WHERE id = ?", idStr).Scan(&simName) if err != nil { if err == sql.ErrNoRows { http.Error(w, "Simulation not found", http.StatusNotFound) } else { http.Error(w, err.Error(), http.StatusInternalServerError) } return } err = r.ParseMultipartForm(500 << 20) // 500 MB max memory/file bounds if err != nil { http.Error(w, "Error parsing form: "+err.Error(), http.StatusBadRequest) return } file, handler, err := r.FormFile("file") if err != nil { http.Error(w, "Error retrieving the file", http.StatusBadRequest) return } defer file.Close() destPath := filepath.Join("../results", simName, handler.Filename) dst, err := os.Create(destPath) if err != nil { http.Error(w, "Error creating destination file: "+err.Error(), http.StatusInternalServerError) return } defer dst.Close() _, err = io.Copy(dst, file) if err != nil { http.Error(w, "Error saving file: "+err.Error(), http.StatusInternalServerError) return } var resID int err = db.QueryRow("SELECT id FROM resources WHERE simulation_id = ? AND filename = ?", idStr, handler.Filename).Scan(&resID) if err == sql.ErrNoRows { _, err = db.Exec("INSERT INTO resources(simulation_id, filename) VALUES(?, ?)", idStr, handler.Filename) if err != nil { log.Println("Error inserting uploaded resource into db:", err) } } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{ "status": "success", "filename": handler.Filename, }) }