package common

import (
	"encoding/json"
	"io"
	"strings"
)

type Commit struct {
	Id      string
	Message string
}

type PushRequest struct {
	Total_Commits int
	Head_Commit   Commit
	Commits       []Commit
	Pusher        User
	Sender        User

	Repository Repository
}

func (h *RequestHandler) parsePushRequest(data io.Reader) *PushRequest {
	if h.HasError() {
		return nil
	}

	var action PushRequest
	h.Error = json.NewDecoder(data).Decode(&action)

	if h.HasError() {
		h.LogError("Got error while parsing: %v", h.Error)
		return nil
	}

	repoIdx := strings.LastIndex(action.Repository.Ssh_Url, "/")
	if repoIdx == -1 || action.Repository.Ssh_Url[repoIdx+1:] != action.Repository.Name+".git" {
		h.LogError("Unexpected URL for SSH repository: '%s'", action.Repository.Name)
		return nil
	}
	h.PrjGit = action.Repository.Ssh_Url[:repoIdx+1] + DefaultGitPrj + ".git"

	h.Log("Request push for repo: %s", action.Repository.Full_Name)
	h.Data = action
	if len(action.Commits) < 1 || len(action.Head_Commit.Id) != 64 {
		h.LogError("Request has no action .... skipping")
		return nil
	}

	return &action
}
