package metrics

import (
	"context"

	structpb "github.com/golang/protobuf/ptypes/struct"
	"github.com/montanaflynn/stats"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"

	pb "code.justin.tv/dta/rockpaperscissors/proto"
)

func init() {
	info := &pb.MetricInfo{
		MetricId:        "num_pull_requests_closed",
		MetricName:      "# of PRs Closed",
		Description:     "Number of Pull Requests closed",
		ValidForProject: true,
		KeyMetric:       false,
	}
	Registry().Register(info, NewNumPullRequestsClosedCalculator)
}

// NumPullRequestsClosedCalculator to calculate how many Jenkins builds a project made.
type NumPullRequestsClosedCalculator struct {
	ProjectMetadataServer pb.ProjectMetadataServiceServer
	EventServer           pb.EventServiceServer
}

// NewNumPullRequestsClosedCalculator factory for NumPullRequestsClosedCalculator structs.
func NewNumPullRequestsClosedCalculator(projectMetadataServer pb.ProjectMetadataServiceServer, eventServer pb.EventServiceServer) (Calculator, error) {
	return &NumPullRequestsClosedCalculator{
		ProjectMetadataServer: projectMetadataServer,
		EventServer:           eventServer,
	}, nil
}

func (p *NumPullRequestsClosedCalculator) getDataPointForEvent(event *pb.Event) (float64, error) {
	return 1.0, nil
}

func (p *NumPullRequestsClosedCalculator) getDataPointsForRepo(ctx context.Context, githubRepo string, timerange *pb.TimeRange) ([]float64, error) {
	var dataPoints []float64

	queryResp, err := p.EventServer.QueryEvents(ctx, &pb.QueryEventsRequest{
		Timerange: timerange,
		Type:      "GitHub-pull_request-closed",
		Filters: []*pb.QueryEventsRequest_AttributeFilter{
			&pb.QueryEventsRequest_AttributeFilter{
				Key:   "base_repository",
				Value: githubRepo,
			},
		},
	})
	if err != nil {
		if grpc.Code(err) == codes.NotFound {
			return nil, nil
		}
		return nil, err
	}
	for _, event := range queryResp.GetEvents() {
		dataPoint, err := p.getDataPointForEvent(event)
		if err != nil {
			// TODO: it might be better to just log the error and skip it
			return nil, err
		}
		dataPoints = append(dataPoints, dataPoint)
	}

	return dataPoints, nil
}

func (p *NumPullRequestsClosedCalculator) calculateEntry(ctx context.Context, req *pb.GetMetricRequest, entry *pb.GetMetricResponse_TimeSeriesEntry, githubRepos []string) error {
	var dataPoints []float64

	for _, githubRepo := range githubRepos {
		repoDataPoints, err := p.getDataPointsForRepo(
			ctx, githubRepo, entry.GetTimerange())
		if err != nil {
			return err
		}
		if repoDataPoints != nil {
			dataPoints = append(dataPoints, repoDataPoints...)
		}
	}

	if len(dataPoints) == 0 {
		return nil
	}

	sum, err := stats.Sum(dataPoints)
	if err != nil {
		return errf(codes.Internal, "Error calculating sum: %v", err)
	}

	entry.Value = &structpb.Value{
		Kind: &structpb.Value_NumberValue{
			NumberValue: sum,
		},
	}

	return nil
}

// Calculate the time series and fill out the response.
func (p *NumPullRequestsClosedCalculator) Calculate(ctx context.Context, req *pb.GetMetricRequest, resp *pb.GetMetricResponse) error {
	timeSeries, err := makeTimeSeries(req.Timerange, req.BucketSize, req.IanaTimeZone)
	if err != nil {
		return errf(codes.InvalidArgument,
			"Found inappropriate time range: %v", err)
	}
	resp.TimeSeries = timeSeries
	resp.TimeSeriesUnits = "Pull Requests"

	githubRepos, err := getGitHubReposForProject(ctx, p.ProjectMetadataServer, req.ProjectId)
	if err != nil {
		return err
	}
	if len(githubRepos) == 0 {
		return nil
	}

	sem := make(chan error, len(timeSeries))
	for _, bucket := range timeSeries {
		go func(ctx context.Context, req *pb.GetMetricRequest, entry *pb.GetMetricResponse_TimeSeriesEntry, githubRepos []string) {
			sem <- p.calculateEntry(ctx, req, entry, githubRepos)
		}(ctx, req, bucket, githubRepos)
	}
	for i := 0; i < len(timeSeries); i++ {
		err := <-sem
		if err != nil {
			// TODO: cancel the context to stop any still-processing work?
			return err
		}
	}

	return nil
}
