package main

import (
	"context"
	"log"

	proto "git.xeserv.us/xena/route/proto"
	"git.xeserv.us/xena/route/proto/route"
	"github.com/hashicorp/terraform/helper/schema"
)

func tokenResource() *schema.Resource {
	return &schema.Resource{
		Create: resourceTokenCreate,
		Read:   resourceTokenRead,
		Delete: resourceTokenDelete,
		Exists: resourceTokenExists,

		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"scopes": {
				Type:     schema.TypeList,
				Required: true,
				ForceNew: true,
			},
		},
	}
}

func resourceTokenCreate(d *schema.ResourceData, meta interface{}) error {
	cli := meta.(*route.Client)

	var scps []string

	for _, val := range d.Get("scopes").([]interface{}) {
		sc, ok := val.(string)
		if !ok {
			log.Printf("[INFO] can't decode %#v", sc)
			continue
		}

		scps = append(scps, sc)
	}

	tok, err := cli.Tokens.Put(context.Background(), &proto.Token{Scopes: scps})
	if err != nil {
		return err
	}

	log.Printf("[INFO] created token with scopes %v and ID %s", tok.Scopes, tok.Id)

	return nil
}

func resourceTokenDelete(d *schema.ResourceData, meta interface{}) error {
	cli := meta.(*route.Client)

	tok, err := cli.Tokens.Get(context.Background(), &proto.GetTokenRequest{Id: d.Id()})
	if err != nil {
		return err
	}

	_, err = cli.Tokens.Deactivate(context.Background(), tok)
	if err != nil {
		return err
	}

	return nil
}

func resourceTokenExists(d *schema.ResourceData, meta interface{}) (bool, error) {
	cli := meta.(*route.Client)

	_, err := cli.Tokens.Get(context.Background(), &proto.GetTokenRequest{Id: d.Id()})
	if err != nil {
		return false, err
	}

	return true, nil
}

func resourceTokenRead(d *schema.ResourceData, meta interface{}) error {
	cli := meta.(*route.Client)

	tok, err := cli.Tokens.Get(context.Background(), &proto.GetTokenRequest{Id: d.Id()})
	if err != nil {
		return err
	}

	d.SetId(tok.Id)
	d.Set("body", tok.Body)
	d.Set("active", tok.Active)
	d.Set("scopes", tok.Scopes)

	return nil
}
