// Copyright 2018 The Terraformer Authors.
//
// 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,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package gcp_terraforming

import (
	"context"
	"log"

	"github.com/GoogleCloudPlatform/terraformer/terraform_utils"

	"google.golang.org/api/iterator"

	"cloud.google.com/go/monitoring/apiv3"
	monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3"
)

var monitoringAllowEmptyValues = []string{}

var monitoringAdditionalFields = map[string]string{}

type MonitoringGenerator struct {
	GCPService
}

func (g *MonitoringGenerator) loadAlerts(ctx context.Context, project string) error {

	client, err := monitoring.NewAlertPolicyClient(ctx)
	if err != nil {
		return err
	}

	req := &monitoringpb.ListAlertPoliciesRequest{
		Name: "projects/" + project,
	}

	alertIterator := client.ListAlertPolicies(ctx, req)
	if err != nil {
		return err
	}

	for {
		alert, err := alertIterator.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Println("error with alert:", err)
			continue
		}
		g.Resources = append(g.Resources, terraform_utils.NewResource(
			alert.Name,
			alert.Name,
			"google_monitoring_alert_policy",
			"google",
			map[string]string{
				"name": alert.Name,
			},
			monitoringAllowEmptyValues,
			monitoringAdditionalFields,
		))
	}
	return nil
}

func (g *MonitoringGenerator) loadGroups(ctx context.Context, project string) error {
	client, err := monitoring.NewGroupClient(ctx)
	if err != nil {
		return err
	}

	req := &monitoringpb.ListGroupsRequest{
		Name: "projects/" + project,
	}

	groupsIterator := client.ListGroups(ctx, req)
	for {
		group, err := groupsIterator.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Println("error with group:", err)
			continue
		}
		g.Resources = append(g.Resources, terraform_utils.NewResource(
			group.Name,
			group.Name,
			"google_monitoring_group",
			"google",
			map[string]string{
				"name": group.Name,
			},
			monitoringAllowEmptyValues,
			monitoringAdditionalFields,
		))
	}
	return nil
}

func (g *MonitoringGenerator) loadNotificationChannel(ctx context.Context, project string) error {
	client, err := monitoring.NewNotificationChannelClient(ctx)
	if err != nil {
		return err
	}

	req := &monitoringpb.ListNotificationChannelsRequest{
		Name: "projects/" + project,
	}

	notificationChannelIterator := client.ListNotificationChannels(ctx, req)
	for {
		notificationChannel, err := notificationChannelIterator.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Println("error with notification Channel:", err)
			continue
		}
		g.Resources = append(g.Resources, terraform_utils.NewResource(
			notificationChannel.Name,
			notificationChannel.Name,
			"google_monitoring_notification_channel",
			"google",
			map[string]string{
				"name": notificationChannel.Name,
			},
			monitoringAllowEmptyValues,
			monitoringAdditionalFields,
		))
	}
	return nil
}
func (g *MonitoringGenerator) loadUptimeCheck(ctx context.Context, project string) error {
	client, err := monitoring.NewUptimeCheckClient(ctx)
	if err != nil {
		return err
	}

	req := &monitoringpb.ListUptimeCheckConfigsRequest{
		Parent: "projects/" + project,
	}

	uptimeCheckConfigsIterator := client.ListUptimeCheckConfigs(ctx, req)
	for {
		uptimeCheckConfigs, err := uptimeCheckConfigsIterator.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Println("error with uptimeCheckConfigs:", err)
			continue
		}
		g.Resources = append(g.Resources, terraform_utils.NewResource(
			uptimeCheckConfigs.Name,
			uptimeCheckConfigs.Name,
			"google_monitoring_uptime_check_config",
			"google",
			map[string]string{
				"name": uptimeCheckConfigs.Name,
			},
			monitoringAllowEmptyValues,
			monitoringAdditionalFields,
		))
	}
	return nil
}

// Generate TerraformResources from GCP API,
// from each alert  create 1 TerraformResource
// Need alert name as ID for terraform resource
func (g *MonitoringGenerator) InitResources() error {
	project := g.GetArgs()["project"]
	ctx := context.Background()

	if err := g.loadAlerts(ctx, project); err != nil {
		return err
	}

	if err := g.loadGroups(ctx, project); err != nil {
		return err
	}

	if err := g.loadNotificationChannel(ctx, project); err != nil {
		return err
	}

	if err := g.loadUptimeCheck(ctx, project); err != nil {
		return err
	}

	g.PopulateIgnoreKeys()
	return nil
}
