<commit_before>package api

import (
	"encoding/json"
	"net/http"
	"strings"

	"github.com/MyHomeworkSpace/api-server/data"
	"github.com/MyHomeworkSpace/api-server/errorlog"
	"github.com/labstack/echo"
)

var MainRegistry data.SchoolRegistry

type DetailedSchoolErrorResponse struct {
	Status  string                 `json:"status"`
	Error   string                 `json:"error"`
	Details map[string]interface{} `json:"details"`
}

type SchoolResultResponse struct {
	Status string             `json:"status"`
	School *data.SchoolResult `json:"school"`
}

func routeSchoolsEnroll(w http.ResponseWriter, r *http.Request, ec echo.Context, c RouteContext) {
	if ec.FormValue("school") == "" || ec.FormValue("data") == "" {
		ec.JSON(http.StatusBadRequest, ErrorResponse{"error", "missing_params"})
		return
	}

	// find school
	school, err := MainRegistry.GetSchoolByID(ec.FormValue("school"))
	if err == data.ErrNotFound {
		ec.JSON(http.StatusBadRequest, ErrorResponse{"error", "invalid_params"})
		return
	} else if err != nil {
		errorlog.LogError("enrolling in school", err)
		ec.JSON(http.StatusInternalServerError, ErrorResponse{"error", "internal_server_error"})
		return
	}

	// check we're not already enrolled
	for _, userSchool := range c.User.Schools {
		if userSchool.SchoolID == school.ID() {
			// we are
			ec.JSON(http.StatusBadRequest, ErrorResponse{"error", "already_enrolled"})
			return
		}
	}

	// parse data
	enrollDataString := ec.FormValue("data")
	enrollData := map[string]interface{}{}

	err = json.Unmarshal([]byte(enrollDataString), &enrollData)
	if err != nil {
		ec.JSON(http.StatusBadRequest, ErrorResponse{"error", "invalid_params"})
		return
	}

	// actually do it

	// new transaction
	tx, err := DB.Begin()
	if err != nil {
		errorlog.LogError("enrolling in school", err)
		ec.JSON(http.StatusInternalServerError, ErrorResponse{"error", "internal_server_error"})
		return
	}

	// clear any existing school record
	_, err = tx.Exec("DELETE FROM schools WHERE schoolId = ? AND userId = ?", school.ID(), c.User.ID)
	if err != nil {
		tx.Rollback()

		errorlog.LogError("enrolling in school", err)
		ec.JSON(http.StatusInternalServerError, ErrorResponse{"error", "internal_server_error"})
		return
	}

	// enroll
	result, err := school.Enroll(tx, c.User, enrollData)
	if err != nil {
		tx.Rollback()

		detailedSchoolError, ok := err.(data.DetailedSchoolError)
		if ok {
			// it wants to report something
			ec.JSON(http.StatusOK, DetailedSchoolErrorResponse{"error", detailedSchoolError.Code, detailedSchoolError.Details})
			return
		}

		schoolError, ok := err.(data.SchoolError)
		if ok {
			// it wants to report an error code
			ec.JSON(http.StatusOK, ErrorResponse{"error", schoolError.Code})
			return
		}

		// server error
		errorlog.LogError("enrolling in school", err)
		ec.JSON(http.StatusInternalServerError, ErrorResponse{"error", "internal_server_error"})
		return
	}

	resultDataBytes, err := json.Marshal(result)<commit_msg>allow reenrolling a school in order to update your schedule data<commit_after>package api

import (
	"encoding/json"
	"net/http"
	"strconv"
	"strings"

	"github.com/MyHomeworkSpace/api-server/data"
	"github.com/MyHomeworkSpace/api-server/errorlog"
	"github.com/labstack/echo"
)

var MainRegistry data.SchoolRegistry

type DetailedSchoolErrorResponse struct {
	Status  string                 `json:"status"`
	Error   string                 `json:"error"`
	Details map[string]interface{} `json:"details"`
}

type SchoolResultResponse struct {
	Status string             `json:"status"`
	School *data.SchoolResult `json:"school"`
}

func routeSchoolsEnroll(w http.ResponseWriter, r *http.Request, ec echo.Context, c RouteContext) {
	if ec.FormValue("school") == "" || ec.FormValue("data") == "" {
		ec.JSON(http.StatusBadRequest, ErrorResponse{"error", "missing_params"})
		return
	}

	var err error
	reenroll := false
	if ec.FormValue("reenroll") != "" {
		reenroll, err = strconv.ParseBool(ec.FormValue("reenroll"))
		if err != nil {
			ec.JSON(http.StatusBadRequest, ErrorResponse{"error", "invalid_params"})
			return
		}
	}

	// find school
	school, err := MainRegistry.GetSchoolByID(ec.FormValue("school"))
	if err == data.ErrNotFound {
		ec.JSON(http.StatusBadRequest, ErrorResponse{"error", "invalid_params"})
		return
	} else if err != nil {
		errorlog.LogError("enrolling in school", err)
		ec.JSON(http.StatusInternalServerError, ErrorResponse{"error", "internal_server_error"})
		return
	}

	// check we're not already enrolled
	enrolled := false
	for _, userSchool := range c.User.Schools {
		if userSchool.SchoolID == school.ID() {
			// we are
			enrolled = true
		}
	}

	if reenroll {
		if !enrolled {
			ec.JSON(http.StatusBadRequest, ErrorResponse{"error", "not_enrolled"})
			return
		}
	} else {
		if enrolled {
			ec.JSON(http.StatusBadRequest, ErrorResponse{"error", "already_enrolled"})
			return
		}
	}

	// parse data
	enrollDataString := ec.FormValue("data")
	enrollData := map[string]interface{}{}

	err = json.Unmarshal([]byte(enrollDataString), &enrollData)
	if err != nil {
		ec.JSON(http.StatusBadRequest, ErrorResponse{"error", "invalid_params"})
		return
	}

	// actually do it

	// new transaction
	tx, err := DB.Begin()
	if err != nil {
		errorlog.LogError("enrolling in school", err)
		ec.JSON(http.StatusInternalServerError, ErrorResponse{"error", "internal_server_error"})
		return
	}

	// clear any existing school record
	_, err = tx.Exec("DELETE FROM schools WHERE schoolId = ? AND userId = ?", school.ID(), c.User.ID)
	if err != nil {
		tx.Rollback()

		errorlog.LogError("enrolling in school", err)
		ec.JSON(http.StatusInternalServerError, ErrorResponse{"error", "internal_server_error"})
		return
	}

	if reenroll {
		err := school.Unenroll(tx, c.User)
		if err != nil {
			tx.Rollback()

			errorlog.LogError("enrolling in school - unenrolling before enroll", err)
			ec.JSON(http.StatusInternalServerError, ErrorResponse{"error", "internal_server_error"})
			return
		}
	}

	// enroll
	result, err := school.Enroll(tx, c.User, enrollData)
	if err != nil {
		tx.Rollback()

		detailedSchoolError, ok := err.(data.DetailedSchoolError)
		if ok {
			// it wants to report something
			ec.JSON(http.StatusOK, DetailedSchoolErrorResponse{"error", detailedSchoolError.Code, detailedSchoolError.Details})
			return
		}

		schoolError, ok := err.(data.SchoolError)
		if ok {
			// it wants to report an error code
			ec.JSON(http.StatusOK, ErrorResponse{"error", schoolError.Code})
			return
		}

		// server error
		errorlog.LogError("enrolling in school", err)
		ec.JSON(http.StatusInternalServerError, ErrorResponse{"error", "internal_server_error"})
		return
	}

	resultDataBytes, err := json.Marshal(result)
{'fraction_non_alphanumeric': 0.1357142857142857, 'fraction_numerical': 0.0, 'mean_word_length': 4.218167701863354, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4389013', 'n_tokens_mistral': 2351, 'n_tokens_neox': 2132, 'n_words': 476}