package azurerm

import (
	"fmt"
	"log"

	"encoding/json"

	"github.com/hashicorp/terraform/helper/schema"
	"github.com/hashicorp/terraform/helper/structure"
	"github.com/hashicorp/terraform/helper/validation"
	"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
)

func resourceArmLogicAppTriggerCustom() *schema.Resource {
	return &schema.Resource{
		Create: resourceArmLogicAppTriggerCustomCreateUpdate,
		Read:   resourceArmLogicAppTriggerCustomRead,
		Update: resourceArmLogicAppTriggerCustomCreateUpdate,
		Delete: resourceArmLogicAppTriggerCustomDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

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

			"logic_app_id": {
				Type:         schema.TypeString,
				Required:     true,
				ForceNew:     true,
				ValidateFunc: azure.ValidateResourceID,
			},

			"body": {
				Type:             schema.TypeString,
				Required:         true,
				ValidateFunc:     validation.ValidateJsonString,
				DiffSuppressFunc: structure.SuppressJsonDiff,
			},
		},
	}
}

func resourceArmLogicAppTriggerCustomCreateUpdate(d *schema.ResourceData, meta interface{}) error {
	logicAppId := d.Get("logic_app_id").(string)
	name := d.Get("name").(string)
	bodyRaw := d.Get("body").(string)

	var body map[string]interface{}
	if err := json.Unmarshal([]byte(bodyRaw), &body); err != nil {
		return fmt.Errorf("Error unmarshalling JSON for Custom Trigger %q: %+v", name, err)
	}

	if err := resourceLogicAppTriggerUpdate(d, meta, logicAppId, name, body, "azurerm_logic_app_trigger_custom"); err != nil {
		return err
	}

	return resourceArmLogicAppTriggerCustomRead(d, meta)
}

func resourceArmLogicAppTriggerCustomRead(d *schema.ResourceData, meta interface{}) error {
	id, err := parseAzureResourceID(d.Id())
	if err != nil {
		return err
	}

	resourceGroup := id.ResourceGroup
	logicAppName := id.Path["workflows"]
	name := id.Path["triggers"]

	t, app, err := retrieveLogicAppTrigger(meta, resourceGroup, logicAppName, name)
	if err != nil {
		return err
	}

	if t == nil {
		log.Printf("[DEBUG] Logic App %q (Resource Group %q) does not contain Trigger %q - removing from state", logicAppName, resourceGroup, name)
		d.SetId("")
		return nil
	}

	action := *t

	d.Set("name", name)
	d.Set("logic_app_id", app.ID)

	body, err := json.Marshal(action)
	if err != nil {
		return fmt.Errorf("Error serializing `body` for Trigger %q: %+v", name, err)
	}

	if err := d.Set("body", string(body)); err != nil {
		return fmt.Errorf("Error setting `body` for Trigger %q: %+v", name, err)
	}

	return nil
}

func resourceArmLogicAppTriggerCustomDelete(d *schema.ResourceData, meta interface{}) error {
	id, err := parseAzureResourceID(d.Id())
	if err != nil {
		return err
	}

	resourceGroup := id.ResourceGroup
	logicAppName := id.Path["workflows"]
	name := id.Path["triggers"]

	err = resourceLogicAppTriggerRemove(d, meta, resourceGroup, logicAppName, name)
	if err != nil {
		return fmt.Errorf("Error removing Trigger %q from Logic App %q (Resource Group %q): %+v", name, logicAppName, resourceGroup, err)
	}

	return nil
}
