// Copyright 2022 Fortinet, Inc. All rights reserved.
// Author: Shih-Hsin Huang
// Description: Configure  system address.

package fortiadc

import (
	"fmt"
	"log"
	"strconv"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

func resourceSystemAddress() *schema.Resource {
	return &schema.Resource{
		Read:   resourceSystemAddressRead,
		Update: resourceSystemAddressUpdate,
		Create: resourceSystemAddressCreate,
		Delete: resourceSystemAddressDelete,

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

		Schema: map[string]*schema.Schema{
			"mkey": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
			},
			"ip_max": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
				Optional: true,
			},
			"ip_netmask": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
				Optional: true,
			},
			"type": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
				Optional: true,
			},
			"ip_min": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
				Optional: true,
			},
			"vdom": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
			},
		},
	}
}
func resourceSystemAddressCreate(d *schema.ResourceData, m interface{}) error {
	c := m.(*FortiClient).Client
	c.Retries = 1

	vdom := ""

	if v, ok := d.GetOk("vdom"); ok {
		if s, ok := v.(string); ok {
			vdom = s
		}
	}

	mkey := ""

	t := d.Get("mkey")
	if v, ok := t.(string); ok {
		mkey = v
	} else if v, ok := t.(int); ok {
		mkey = strconv.Itoa(v)
	} else {
		return fmt.Errorf("Error describing SystemAddress: type error")
	}

	obj, err := getObjectSystemAddress(d, c.Fv)
	if err != nil {
		return fmt.Errorf("Error creating SystemAddress resource while getting object: %v", err)
	}

	_, err = c.CreateSystemAddress(obj, vdom)
	if err != nil {
		return fmt.Errorf("Error creating SystemAddress resource: %v", err)
	}

	d.SetId(mkey)

	return resourceSystemAddressRead(d, m)
}
func resourceSystemAddressUpdate(d *schema.ResourceData, m interface{}) error {
	mkey := d.Id()
	c := m.(*FortiClient).Client
	c.Retries = 1

	vdom := ""

	if v, ok := d.GetOk("vdom"); ok {
		if s, ok := v.(string); ok {
			vdom = s
		}
	}

	obj, err := getObjectSystemAddress(d, c.Fv)
	if err != nil {
		return fmt.Errorf("Error updating SystemAddress resource while getting object: %v", err)
	}

	_, err = c.UpdateSystemAddress(obj, mkey, vdom)
	if err != nil {
		return fmt.Errorf("Error updating SystemAddress resource: %v", err)
	}

	return resourceSystemAddressRead(d, m)
}
func resourceSystemAddressDelete(d *schema.ResourceData, m interface{}) error {
	mkey := d.Id()

	c := m.(*FortiClient).Client
	c.Retries = 1

	vdom := ""
	if v, ok := d.GetOk("vdom"); ok {
		if s, ok := v.(string); ok {
			vdom = s
		}
	}

	err := c.DeleteSystemAddress(mkey, vdom)
	if err != nil {
		return fmt.Errorf("Error deleting SystemAddress resource: %v", err)
	}

	d.SetId("")

	return nil
}
func resourceSystemAddressRead(d *schema.ResourceData, m interface{}) error {
	mkey := d.Id()

	c := m.(*FortiClient).Client
	c.Retries = 1

	vdom := ""

	if v, ok := d.GetOk("vdom"); ok {
		if s, ok := v.(string); ok {
			vdom = s
		}
	}

	o, err := c.ReadSystemAddress(mkey, vdom)
	if err != nil {
		return fmt.Errorf("Error reading SystemAddress resource: %v", err)
	}

	if o == nil {
		log.Printf("[WARN] resource (%s) not found, removing from state", d.Id())
		d.SetId("")
		return nil
	}

	err = refreshObjectSystemAddress(d, o, c.Fv)
	if err != nil {
		return fmt.Errorf("Error reading SystemAddress resource from API: %v", err)
	}
	return nil
}
func flattenSystemAddressMkey(v interface{}, d *schema.ResourceData, pre string, sv string) interface{} {
	return v
}

func flattenSystemAddressIpMax(v interface{}, d *schema.ResourceData, pre string, sv string) interface{} {
	return v
}

func flattenSystemAddressIpNetmask(v interface{}, d *schema.ResourceData, pre string, sv string) interface{} {
	if v1, ok := d.GetOkExists(pre); ok && v != nil {
		if s, ok := v1.(string); ok {
			v = validateConvIPMask2CIDR(s, v.(string))
			return v
		}
	}

	return v
}

func flattenSystemAddressType(v interface{}, d *schema.ResourceData, pre string, sv string) interface{} {
	return v
}

func flattenSystemAddressIpMin(v interface{}, d *schema.ResourceData, pre string, sv string) interface{} {
	return v
}

func refreshObjectSystemAddress(d *schema.ResourceData, o map[string]interface{}, sv string) error {
	var err error

	if err = d.Set("mkey", flattenSystemAddressMkey(o["mkey"], d, "mkey", sv)); err != nil {
		if !fortiAPIPatch(o["mkey"]) {
			return fmt.Errorf("Error reading mkey: %v", err)
		}
	}

	if err = d.Set("ip_max", flattenSystemAddressIpMax(o["ip-max"], d, "ip_max", sv)); err != nil {
		if !fortiAPIPatch(o["ip-max"]) {
			return fmt.Errorf("Error reading ip-max: %v", err)
		}
	}

	if err = d.Set("ip_netmask", flattenSystemAddressIpNetmask(o["ip-netmask"], d, "ip_netmask", sv)); err != nil {
		if !fortiAPIPatch(o["ip-netmask"]) {
			return fmt.Errorf("Error reading ip-netmask: %v", err)
		}
	}

	if err = d.Set("type", flattenSystemAddressType(o["type"], d, "type", sv)); err != nil {
		if !fortiAPIPatch(o["type"]) {
			return fmt.Errorf("Error reading type: %v", err)
		}
	}

	if err = d.Set("ip_min", flattenSystemAddressIpMin(o["ip-min"], d, "ip_min", sv)); err != nil {
		if !fortiAPIPatch(o["ip-min"]) {
			return fmt.Errorf("Error reading ip-min: %v", err)
		}
	}

	return nil
}

func expandSystemAddressMkey(d *schema.ResourceData, v interface{}, pre string, sv string) (interface{}, error) {
	return v, nil
}

func expandSystemAddressIpMax(d *schema.ResourceData, v interface{}, pre string, sv string) (interface{}, error) {
	return v, nil
}

func expandSystemAddressIpNetmask(d *schema.ResourceData, v interface{}, pre string, sv string) (interface{}, error) {
	return v, nil
}

func expandSystemAddressType(d *schema.ResourceData, v interface{}, pre string, sv string) (interface{}, error) {
	return v, nil
}

func expandSystemAddressIpMin(d *schema.ResourceData, v interface{}, pre string, sv string) (interface{}, error) {
	return v, nil
}

func getObjectSystemAddress(d *schema.ResourceData, sv string) (*map[string]interface{}, error) {
	obj := make(map[string]interface{})

	if v, ok := d.GetOk("mkey"); ok {
		t, err := expandSystemAddressMkey(d, v, "mkey", sv)
		if err != nil {
			return &obj, err
		} else if t != nil {
			obj["mkey"] = t
		}
	}

	if v, ok := d.GetOk("ip_max"); ok {
		t, err := expandSystemAddressIpMax(d, v, "ip_max", sv)
		if err != nil {
			return &obj, err
		} else if t != nil {
			obj["ip-max"] = t
		}
	}

	if v, ok := d.GetOk("ip_netmask"); ok {
		t, err := expandSystemAddressIpNetmask(d, v, "ip_netmask", sv)
		if err != nil {
			return &obj, err
		} else if t != nil {
			obj["ip-netmask"] = t
		}
	}

	if v, ok := d.GetOk("type"); ok {
		t, err := expandSystemAddressType(d, v, "type", sv)
		if err != nil {
			return &obj, err
		} else if t != nil {
			obj["type"] = t
		}
	}

	if v, ok := d.GetOk("ip_min"); ok {
		t, err := expandSystemAddressIpMin(d, v, "ip_min", sv)
		if err != nil {
			return &obj, err
		} else if t != nil {
			obj["ip-min"] = t
		}
	}

	return &obj, nil
}
