/*
Copyright (c) 2019-2022 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Kasim Baybikov, <kmbaybikov@basistech.ru>

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.
*/

/*
Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud
Orchestration Technology) with Terraform by Hashicorp.

Source code: https://repository.basistech.ru/BASIS/terraform-provider-decort

Please see README.md to learn where to place source code so that it
builds seamlessly.

Documentation: https://repository.basistech.ru/BASIS/terraform-provider-decort/wiki
*/

package image

import (
	"context"
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
	log "github.com/sirupsen/logrus"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/disks"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/image"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudapi/tasks"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/status"
)

func resourceImageFromPlatformDiskCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	diskId := uint64(d.Get("disk_id").(int))
	name := d.Get("name").(string)

	log.Debugf("resourceImageFromPlatformDiskCreate: called for image %s", name)

	err := existDiskID(ctx, diskId, m)
	if err != nil {
		return diag.Errorf("resourceImageFromPlatformDiskCreate: can't create Image: %v", err)
	}

	if _, ok := d.GetOk("account_id"); ok {
		haveAccountID, err := existAccountID(ctx, d, m)
		if err != nil {
			return diag.FromErr(err)
		}

		if !haveAccountID {
			return diag.Errorf("resourceImageFromPlatformDiskCreate: can't create Image because AccountID %d is not allowed or does not exist", d.Get("account_id").(int))
		}
	}

	c := m.(*controller.ControllerCfg)
	req := disks.FromPlatformDiskRequest{
		DiskID:    diskId,
		Name:      name,
		BootType:  d.Get("boot_type").(string),
		ImageType: d.Get("type").(string),
		Bootable:  d.Get("bootable").(bool), // default value - true
	}

	if username, ok := d.GetOk("username"); ok {
		req.Username = username.(string)
	}
	if password, ok := d.GetOk("password"); ok {
		req.Password = password.(string)
	}
	if accountId, ok := d.GetOk("account_id"); ok {
		req.AccountID = uint64(accountId.(int))
	}
	if poolName, ok := d.GetOk("pool_name"); ok {
		req.PoolName = poolName.(string)
	}
	if hotresize, ok := d.GetOk("hot_resize"); ok {
		req.HotResize = hotresize.(bool)
	}

	var imageId uint64
	asyncMode := d.Get("async_mode").(bool)
	if !asyncMode {
		imageId, err = c.CloudAPI().Disks().FromPlatformDisk(ctx, req)
		if err != nil {
			d.SetId("")
			return diag.FromErr(err)
		}
	} else {
		taskId, err := c.CloudAPI().Disks().FromPlatformDiskAsync(ctx, req)
		if err != nil {
			d.SetId("")
			return diag.FromErr(err)
		}

		taskReq := tasks.GetRequest{
			AuditID: strings.Trim(taskId, `"`),
		}

		for {
			task, err := c.CloudAPI().Tasks().Get(ctx, taskReq)
			if err != nil {
				return diag.FromErr(err)
			}

			log.Debugf("resourceImageFromPlatformDiskCreate: instance creating - %s", task.Stage)

			if task.Completed {
				if task.Error != "" {
					return diag.FromErr(fmt.Errorf("cannot create image instance: %v", task.Error))
				}

				id, err := task.Result.ID()
				imageId = uint64(id)
				if err != nil {
					return diag.FromErr(err)
				}
				break
			}

			time.Sleep(time.Second * 20)
		}
	}

	d.SetId(strconv.FormatUint(imageId, 10))
	d.Set("image_id", imageId)

	_, err = utilityImageCheckPresence(ctx, d, m)
	if err != nil {
		return diag.FromErr(err)
	}

	return resourceImageFromPlatformDiskRead(ctx, d, m)
}

func resourceImageFromPlatformDiskRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceImageFromPlatformDiskRead: called for %s id: %s", d.Get("name").(string), d.Id())

	img, err := utilityImageCheckPresence(ctx, d, m)
	if img == nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	switch img.Status {
	case status.Modeled:
		return diag.Errorf("The image is in status: %s, please, contact support for more information", img.Status)
	case status.Creating:
	case status.Created:
	case status.Destroyed, status.Purged:
		d.SetId("")
		return diag.Errorf("The resource cannot be updated because it has been destroyed")
	}

	flattenImage(d, img)

	return nil
}

func resourceImageFromPlatformDiskDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceImageFromPlatformDiskDelete: called for %s, id: %s", d.Get("name").(string), d.Id())

	_, err := utilityImageCheckPresence(ctx, d, m)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	c := m.(*controller.ControllerCfg)
	req := image.DeleteRequest{
		ImageID: uint64(d.Get("image_id").(int)),
	}

	_, err = c.CloudAPI().Image().Delete(ctx, req)
	if err != nil {
		return diag.FromErr(err)
	}

	d.SetId("")

	return nil
}

func resourceImageFromPlatformDiskUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceImageFromPlatformDiskUpdate: called for %s, id: %s", d.Get("name").(string), d.Id())

	// we do not allow change of disk_id, but allow resource update after import
	old, _ := d.GetChange("disk_id")
	if old.(int) != 0 && d.HasChange("disk_id") {
		return diag.Errorf("resourceImageFromPlatformDiskUpdate: can't update Image because disk_id is not allowed to be changed")
	}

	image, err := utilityImageCheckPresence(ctx, d, m)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	switch image.Status {
	case status.Modeled:
		return diag.Errorf("The image is in status: %s, please, contact support for more information", image.Status)
	case status.Creating:
	case status.Created:
	case status.Destroyed, status.Purged:
		d.SetId("")
		return diag.Errorf("The resource cannot be updated because it has been destroyed")
	}

	if d.HasChange("name") {
		err := resourceImageRename(ctx, d, m)
		if err != nil {
			return diag.FromErr(err)
		}
	}

	return resourceImageFromPlatformDiskRead(ctx, d, m)
}

func ResourceImageFromPlatformDisk() *schema.Resource {
	return &schema.Resource{
		SchemaVersion: 2,

		CreateContext: resourceImageFromPlatformDiskCreate,
		ReadContext:   resourceImageFromPlatformDiskRead,
		UpdateContext: resourceImageFromPlatformDiskUpdate,
		DeleteContext: resourceImageFromPlatformDiskDelete,

		Importer: &schema.ResourceImporter{
			StateContext: schema.ImportStatePassthroughContext,
		},

		Timeouts: &schema.ResourceTimeout{
			Create:  &constants.Timeout30m,
			Read:    &constants.Timeout900s,
			Update:  &constants.Timeout900s,
			Delete:  &constants.Timeout900s,
			Default: &constants.Timeout900s,
		},

		Schema: resourceImageFromPlatformDiskSchemaMake(),
		StateUpgraders: []schema.StateUpgrader{
			{
				Type:    resourceImageFromBlankDiskSchemaV1().CoreConfigSchema().ImpliedType(),
				Upgrade: resourcePresentToUpgradeV1,
				Version: 1,
			},
		},
	}
}

func resourceImageFromPlatformDiskSchemaMake() map[string]*schema.Schema {
	return map[string]*schema.Schema{
		"disk_id": {
			Type:        schema.TypeInt,
			Required:    true,
			Description: "Disk Id",
		},
		"name": {
			Type:        schema.TypeString,
			Required:    true,
			Description: "Name of the rescue disk",
		},
		"boot_type": {
			Type:         schema.TypeString,
			Required:     true,
			ValidateFunc: validation.StringInSlice([]string{"bios", "uefi"}, true),
			Description:  "Boot type of image BIOS or UEFI",
		},
		"type": {
			Type:         schema.TypeString,
			Required:     true,
			ValidateFunc: validation.StringInSlice([]string{"linux", "windows", "unknown"}, true),
			Description:  "Image type linux, windows or unknown",
		},
		"username": {
			Type:        schema.TypeString,
			Optional:    true,
			Computed:    true,
			Description: "Optional username for the image",
		},
		"password": {
			Type:        schema.TypeString,
			Optional:    true,
			Computed:    true,
			Description: "Optional password for the image",
		},
		"account_id": {
			Type:        schema.TypeInt,
			Optional:    true,
			Computed:    true,
			Description: "AccountId to make the image exclusive",
		},
		"sep_id": {
			Type:        schema.TypeInt,
			Computed:    true,
			Description: "storage endpoint provider ID",
		},
		"pool_name": {
			Type:        schema.TypeString,
			Optional:    true,
			Computed:    true,
			Description: "pool for image create",
		},
		"bootable": {
			Type:        schema.TypeBool,
			Optional:    true,
			Default:     true,
			Description: "bootable image",
		},
		"hot_resize": {
			Type:        schema.TypeBool,
			Optional:    true,
			Computed:    true,
			Description: "Does this machine supports hot resize",
		},
		"async_mode": {
			Type:        schema.TypeBool,
			Optional:    true,
			Default:     false,
			Description: "create an image in async/sync mode",
		},

		"architecture": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"image_id": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"unc_path": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"ckey": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"acl": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"compute_ci_id": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"cd_presented_to": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"deleted_time": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"desc": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"drivers": {
			Type:     schema.TypeList,
			Computed: true,
			Elem: &schema.Schema{
				Type: schema.TypeString,
			},
		},
		"enabled": {
			Type:     schema.TypeBool,
			Computed: true,
		},
		"gid": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"guid": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"history": {
			Type:     schema.TypeList,
			Computed: true,
			Elem: &schema.Resource{
				Schema: map[string]*schema.Schema{
					"guid": {
						Type:     schema.TypeString,
						Computed: true,
					},
					"id": {
						Type:     schema.TypeInt,
						Computed: true,
					},
					"timestamp": {
						Type:     schema.TypeInt,
						Computed: true,
					},
				},
			},
		},
		"last_modified": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"link_to": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"links_to": {
			Type:     schema.TypeList,
			Computed: true,
			Elem: &schema.Schema{
				Type: schema.TypeInt,
			},
		},
		"milestones": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"image_name": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"network_interface_naming": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"provider_name": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"purge_attempts": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"present_to": {
			Type:     schema.TypeMap,
			Computed: true,
			Elem: &schema.Schema{
				Type: schema.TypeInt,
			},
		},
		"res_id": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"rescuecd": {
			Type:     schema.TypeBool,
			Computed: true,
		},
		"shared_with": {
			Type:     schema.TypeList,
			Computed: true,
			Elem: &schema.Schema{
				Type: schema.TypeInt,
			},
		},
		"size": {
			Type:     schema.TypeInt,
			Computed: true,
		},
		"snapshot_id": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"status": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"tech_status": {
			Type:     schema.TypeString,
			Computed: true,
		},
		"to_clean": {
			Type:     schema.TypeBool,
			Computed: true,
		},
		"version": {
			Type:     schema.TypeString,
			Computed: true,
		},
	}
}
