package templategen

import (
	"fmt"
	"github.com/Pena-Co-Ltd/amocrm_templategen_back/amo"
	docTemp "github.com/opencontrol/doc-template"
	"io"
	"net/http"
	"os"
	"time"
)

const (
	TempDownloaded = "./tmp/downloaded"
	TempGenerated  = "./tmp/generated"
)

func GenerateDocName(name, userID string) string {
	return fmt.Sprintf("%v_%v_%v.docx", name, userID, time.Now().UnixNano())
}

func GenerateFile(filename string, data interface{}) error {
	dc, err := docTemp.GetTemplate(TempDownloaded + "/" + filename)
	if err != nil {
		return err
	}

	dc.Parse()

	return dc.Execute(TempGenerated+"/"+filename, data)
}

// DownloadDocument - загружает документ в filepath из url
func DownloadDocument(filepath, url string) error {
	resp, err := http.Get(url)

	if err != nil {
		return err
	}
	defer resp.Body.Close()

	// Create the file
	out, err := os.Create(filepath)
	if err != nil {
		return err
	}
	defer out.Close()

	// Write the body to file
	_, err = io.Copy(out, resp.Body)
	return err
}

func DeleteDocument(filepath string) error {
	return os.Remove(filepath)
}

func ShareDocument(filepath string) (error, string) {
	return nil, ""
}

func AmoLeadFieldsToRuMap(data *amo.Lead) map[string]interface{} {
	result := map[string]interface{}{
		"ID":        data.Id,
		"Название":  data.Name,
		"Бюджет":    data.Price,
		"Создатель": data.CreatedBy,
	}

	for k, v := range AmoCustomFieldsToMap(data.CustomFieldsValues) {
		result[k] = v
	}

	return result
}

func AmoContactsFieldsToRuMap(data []amo.Contact) []interface{} {
	result := []interface{}{}

	for _, contact := range data {
		contactMap := map[string]interface{}{
			"ФИО":     contact.Name,
			"Имя":     contact.FirstName,
			"Фамилия": contact.LastName,
		}

		for k, v := range AmoCustomFieldsToMap(contact.CustomFieldsValues) {
			contactMap[k] = v
		}

		result = append(result, contactMap)
	}

	return result
}

func AmoCustomFieldsToMap(data []amo.CustomField) map[string]interface{} {
	result := map[string]interface{}{}
	for _, field := range data {
		switch len(field.Values) {
		case 0:
			result[field.FieldName] = ""
		case 1:
			result[field.FieldName] = field.Values[0].Value
		default:
			result[field.FieldName] = field.Values
		}
	}

	return result
}

func AmoCompaniesFieldsToRuMap(data []amo.Company) []interface{} {
	result := []interface{}{}
	for _, company := range data {
		companyMap := map[string]interface{}{
			"Название": company.Name,
		}

		for k, v := range AmoCustomFieldsToMap(company.CustomFieldsValues) {
			companyMap[k] = v
		}

		result = append(result, companyMap)
	}

	return result
}
