/**
 * Provides a service class with methods to interact with Address domain class.
 * Address stores the address for various objects in the database.
 */
class AddressService {

    boolean transactional = false

    def getAddress() {
        """${this.street1}
        ${this.street2}
        ${this.city}
        ${this.state}
        ${this.postCode}
        ${this.country}"""

    }

    def create(params) {
        def result = [:]
        def fail = { Map m ->
            result.error = [ code: m.code, args: ["Address", params.id] ]
            return result
        }

        if(!checkForOwner(params))
            return fail(code:"address.owner.not.found")

        result.addressInstance = new Address()
        result.addressInstance.properties = params

        // success
        return result
    }

    def save(params) {
        def result = [:]
        def fail = { Map m ->
            if(result.addressInstance && m.field)
                result.addressInstance.errors.rejectValue(m.field, m.code)
            result.error = [ code: m.code, args: ["Address", params.id] ]
            return result
        }

        if(!checkForOwner(params))
            return fail(code:"address.owner.not.found")

        result.addressInstance = new Address(params)

        if(result.addressInstance.hasErrors() || !result.addressInstance.save(flush: true))
            return fail(code:"default.create.failure")

        // success
        return result
    }

    private checkForOwner(params) {

        if(params.manufacturer?.id)
            return Manufacturer.exists(params.manufacturer.id)
        if(params.supplier?.id)
            return Supplier.exists(params.supplier.id)
        if(params.person?.id)
            return Person.exists(params.person.id)
        if(params.site?.id)
            return Site.exists(params.site.id)

        return false
    }


} // end of class
