package entities

import (
	"strings"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type Address struct {
	BaseEntity

	Address1   string `gorm:"column:address_1"`
	Address2   string `gorm:"column:address_2"`
	PostalCode string
	UnitNumber string
	CountryID  int64
	Country    Country
	Deactivate bool

	SubLevelLocations []Location `gorm:"many2many:address_sub_levels;"`
}

func (b *Address) BeforeCreate(tx *gorm.DB) (err error) {
	tx.Statement.AddClause(clause.OnConflict{
		UpdateAll: true,
	})
	return nil
}

func (b *Address) ToString() string {
	address := strings.TrimSpace(b.UnitNumber + " " + b.Address1 + " " + b.Address2)
	for i := len(b.SubLevelLocations) - 1; i >= 0; i-- {
		address += ", " + b.SubLevelLocations[i].InternationalName
	}
	address += " " + b.PostalCode
	return address
}

func (b *Address) ToStringLocalized() string {
	address := strings.TrimSpace(b.UnitNumber + " " + b.Address1 + " " + b.Address2)
	for i := len(b.SubLevelLocations) - 1; i >= 0; i-- {
		address += ", " + b.SubLevelLocations[i].LocalizedName
	}
	address += " " + b.PostalCode
	return address
}

func (b *Address) SortSubLevelLocations() []Location {
	n := len(b.SubLevelLocations)
	if n < 2 {
		return b.SubLevelLocations
	}

	locations := make([]Location, 0)
	var parentId int64 = 0
	for i := 0; i < n; i++ {
		for _, v := range b.SubLevelLocations {
			if v.ParentID == parentId {
				locations = append(locations, v)
				parentId = v.ID.ToInt64()
			}
		}
	}
	return locations
}
