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 routeResource() *schema.Resource {
	return &schema.Resource{
		Create: resourceRouteCreate,
		Read:   resourceRouteRead,
		Delete: resourceRouteDelete,
		Exists: resourceRouteExists,

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

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

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

	rt, err := cli.Routes.Put(context.Background(), &proto.Route{
		Host: d.Get("host").(string),
	})

	if err != nil {
		return err
	}

	log.Printf("[INFO] created route for host %s with ID %s", rt.Host, rt.Id)

	return nil
}

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

	rt, err := cli.Routes.Get(context.Background(), &proto.GetRouteRequest{Id: d.Id()})
	if err != nil {
		return err
	}

	_, err = cli.Routes.Delete(context.Background(), rt)
	if err != nil {
		return err
	}

	log.Printf("[INFO] deleted route for host %s with ID %s", rt.Host, rt.Id)

	return nil
}

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

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

	return true, nil
}

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

	rt, err := cli.Routes.Get(context.Background(), &proto.GetRouteRequest{Id: d.Id()})
	if err != nil {
		return err
	}

	d.SetId(rt.Id)
	d.Set("host", rt.Host)
	d.Set("creator", rt.Creator)

	return nil
}
