/*
 * Copyright 2021 PingCAP, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"os"
	"strings"
	"time"

	runtime "github.com/aws/aws-lambda-go/lambda"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/sqs"
	"github.com/jinzhu/now"
)

type Out struct {
	StartUnix int64 `json:"start_unix"`
	EndUnix   int64 `json:"end_unix"`
	Success   int   `json:"success"`
	Fail      int   `json:"fail"`
	Total     int   `json:"total"`
}

func process(ctx context.Context) (*Out, error) {
	// request rate limit

	ak := os.Getenv("PAGERDUTY_AK")
	qName := os.Getenv("QUEUE_NAME")
	mode := os.Getenv("MODE")
	drainSince := os.Getenv("DRAIN_SINCE")
	drainUntil := os.Getenv("DRAIN_UNTIL")
	msgGroupID := os.Getenv("MESSAGE_GROUP_ID")

	// validate env
	if len(ak) == 0 {
		return nil, errors.New("PAGERDUTY_AK is empty")
	}
	if len(qName) == 0 {
		return nil, errors.New("QUEUE_NAME is empty")
	}
	if len(msgGroupID) == 0 {
		return nil, errors.New("MESSAGE_GROUP_ID is empty")
	}

	loc, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		log.Printf("LoadLocation error: %+v\n", err)
		return nil, err
	}
	endTime := now.With(time.Now().In(loc)).BeginningOfDay()
	startTime := endTime.AddDate(0, 0, -1)

	sess := session.Must(session.NewSessionWithOptions(session.Options{
		SharedConfigState: session.SharedConfigEnable,
	}))
	sqsCli := sqs.New(sess)

	out, err := sqsCli.GetQueueUrl(&sqs.GetQueueUrlInput{
		QueueName: aws.String(qName),
	})
	if err != nil {
		return nil, err
	}
	collector := New(ak, startTime, endTime)
	collector.SetDrainRange(drainSince, drainUntil)
	sink := collector.GetSink()
	log.Printf("run in mode %v, drain range %v, %v\n", mode, drainSince, drainUntil)
	switch strings.ToLower(mode) {
	case "drain":
		go func() {
			if err := collector.drain(ctx); err != nil {
				log.Println(err)
			}
		}()
	default:
		go func() {
			if err := collector.collect(ctx); err != nil {
				log.Println(err)
			}
		}()
	}
	success := 0
	fail := 0
	for {
		select {
		case s, ok := <-sink:
			if !ok {
				out := Out{
					StartUnix: startTime.Unix(),
					EndUnix:   endTime.Unix(),
					Success:   success,
					Fail:      fail,
					Total:     success + fail,
				}
				log.Printf("out: %+v\n", out)
				return &out, nil
			}
			// send alert info to sqs
			bs, err := json.Marshal(s)
			if err != nil {
				fail++
				continue
			}
			msg := new(sqs.SendMessageInput)
			msg.SetMessageBody(string(bs))
			msg.SetQueueUrl(*out.QueueUrl)
			msg.SetMessageGroupId(msgGroupID)
			// AlertID and timestamp can be used as duplication id
			dupID := fmt.Sprintf("%s%v", s.AlertID, time.Now().Nanosecond())
			msg.SetMessageDeduplicationId(dupID)
			if _, err = sqsCli.SendMessage(msg); err != nil {
				log.Println(err)
				fail++
			} else {
				success++
			}
		}
	}
}

func main() {
	runtime.Start(process)
}
