/*
Copyright (c) 2019-2023 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>
Sergey Kisil, <svkisil@digitalenergy.online>

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 user

import (
	"strconv"

	log "github.com/sirupsen/logrus"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/user"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/flattens"
)

func flattenUserDataSource(d *schema.ResourceData, details *user.ItemUser) {
	log.Debugf("flattenUser: decoded User ID %s",
		details.ID)

	d.Set("user_id", details.ID)
	d.Set("ckey", details.CKey)
	d.Set("meta", flattens.FlattenMeta(details.Meta))
	d.Set("api_access", details.APIAccess)
	d.Set("active", details.Active)
	d.Set("authkey", details.AuthKey)
	d.Set("auth_keys", flattenItemUser(details.AuthKeys))
	d.Set("blocked", details.Blocked)
	d.Set("data", details.Data)
	d.Set("description", details.Description)
	d.Set("domain", details.Domain)
	d.Set("emails", details.Emails)
	d.Set("gid", details.GID)
	d.Set("groups", details.Groups)
	d.Set("guid", details.GUID)
	d.Set("last_check", details.LastCheck)
	d.Set("mobile", flattenItemUser(details.Mobile))
	d.Set("password", details.Password)
	d.Set("protected", details.Protected)
	d.Set("roles", flattenItemUser(details.Roles))
	d.Set("service_account", details.ServiceAccount)
	d.Set("xmpp", flattenItemUser(details.XMPP))
}

func flattenUserResource(d *schema.ResourceData, details *user.ItemUser) {
	log.Debugf("flattenUser: decoded User ID %s",
		details.ID)

	d.Set("username", details.ID)
	d.Set("ckey", details.CKey)
	d.Set("meta", flattens.FlattenMeta(details.Meta))
	d.Set("apiaccess", flattenAPIAcess(details.APIAccess))
	d.Set("active", details.Active)
	d.Set("authkey", details.AuthKey)
	d.Set("auth_keys", flattenItemUser(details.AuthKeys))
	d.Set("blocked", details.Blocked)
	d.Set("data", details.Data)
	d.Set("description", details.Description)
	d.Set("domain", details.Domain)
	d.Set("emailaddress", details.Emails[0])
	d.Set("gid", details.GID)
	d.Set("groups", details.Groups)
	d.Set("guid", details.GUID)
	d.Set("last_check", details.LastCheck)
	d.Set("mobile", flattenItemUser(details.Mobile))
	d.Set("protected", details.Protected)
	d.Set("roles", flattenItemUser(details.Roles))
	d.Set("service_account", details.ServiceAccount)
	d.Set("xmpp", flattenItemUser(details.XMPP))
}

func flattenItemUser(m []interface{}) []string {
	output := []string{}
	for _, item := range m {
		switch d := item.(type) {
		case string:
			output = append(output, d)
		case int:
			output = append(output, strconv.Itoa(d))
		case int64:
			output = append(output, strconv.FormatInt(d, 10))
		case float64:
			output = append(output, strconv.FormatInt(int64(d), 10))
		default:
			output = append(output, "")
		}
	}
	return output
}

func flattenUserGetAudits(audits *user.ListAudits) []map[string]interface{} {
	log.Debug("flattenUserGetAudits")

	res := make([]map[string]interface{}, 0, len(audits.Data))
	for _, item := range audits.Data {
		temp := map[string]interface{}{
			"call":          item.Call,
			"response_time": item.ResponseTime,
			"status_code":   item.StatusCode,
			"time":          item.Time,
			"guid":          item.GUID,
		}
		res = append(res, temp)
	}

	return res
}

func flattenUserList(users *user.ListUsers) []map[string]interface{} {
	log.Debug("flattenUserList")

	res := make([]map[string]interface{}, 0, len(users.Data))
	for _, item := range users.Data {
		temp := map[string]interface{}{
			"ckey":            item.CKey,
			"meta":            flattens.FlattenMeta(item.Meta),
			"apiaccess":       item.APIAccess,
			"active":          item.Active,
			"authkey":         item.AuthKey,
			"authkeys":        flattenItemUser(item.AuthKeys),
			"blocked":         item.Blocked,
			"data":            item.Data,
			"description":     item.Description,
			"domain":          item.Domain,
			"emails":          item.Emails,
			"gid":             item.GID,
			"groups":          item.Groups,
			"guid":            item.GUID,
			"user_id":         item.ID,
			"last_check":      item.LastCheck,
			"mobile":          flattenItemUser(item.Mobile),
			"password":        item.Password,
			"protected":       item.Protected,
			"roles":           flattenItemUser(item.Roles),
			"service_account": item.ServiceAccount,
			"xmpp":            flattenItemUser(item.XMPP),
		}
		res = append(res, temp)
	}

	return res
}

func flattenAPIAcess(in map[string]string) []int {

	res := make([]int, 0, len(in))

	for i := range in {
		num, err := strconv.Atoi(i)
		if err != nil {

			log.Errorf("flattenAPIAcess: unable to convert %s to digit %v", i, err)

			return nil
		}
		res = append(res, num)
	}
	return res

}
