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_builds",
		MetricName:      "# of Builds",
		Description:     "How many Jenkins builds were made?",
		ValidForProject: true,
		KeyMetric:       true,
	}
	Registry().Register(info, NewNumBuildsCalculator)
}

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

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

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

func (p *NumBuildsCalculator) getDataPointsForJob(ctx context.Context, jenkinsJob string, timerange *pb.TimeRange) ([]float64, error) {
	var dataPoints []float64

	queryResp, err := p.EventServer.QueryEvents(ctx, &pb.QueryEventsRequest{
		Timerange: timerange,
		Type:      "JenkinsBuildStats",
		Filters: []*pb.QueryEventsRequest_AttributeFilter{
			&pb.QueryEventsRequest_AttributeFilter{
				Key:   "jenkins_job_name",
				Value: jenkinsJob,
			},
		},
	})
	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 *NumBuildsCalculator) calculateEntry(ctx context.Context, req *pb.GetMetricRequest, entry *pb.GetMetricResponse_TimeSeriesEntry, jenkinsJobs []string) error {
	var dataPoints []float64

	for _, jenkinsJob := range jenkinsJobs {
		jobDataPoints, err := p.getDataPointsForJob(
			ctx, jenkinsJob, entry.GetTimerange())
		if err != nil {
			return err
		}
		if jobDataPoints != nil {
			dataPoints = append(dataPoints, jobDataPoints...)
		}
	}

	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 *NumBuildsCalculator) 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 = "Builds"

	jenkinsJobs, err := getJenkinsJobsForProject(ctx, p.ProjectMetadataServer, req.ProjectId)
	if err != nil {
		return err
	}
	if len(jenkinsJobs) == 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, jenkinsJobs []string) {
			sem <- p.calculateEntry(ctx, req, entry, jenkinsJobs)
		}(ctx, req, bucket, jenkinsJobs)
	}
	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
}
