/**
 * Provides a service class with methods to interact with the Contact domain class.
 * Contact stores contact details for various objects in the database.
 */
class ContactService {

    boolean transactional = false

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

        result.contactInstance = Contact.get(params.id)

        if(!result.contactInstance)
            return fail(code:"default.not.found")

        result.ownerInstance = getOwner(result.contactInstance)

        try {
            result.contactInstance.delete(flush:true)
            return result //Success.
        }
        catch(org.springframework.dao.DataIntegrityViolationException e) {
            return fail(code:"default.delete.failure")
        }

    }

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

        result.ownerInstance = getOwner(params)
        if(!result.ownerInstance)
            return fail(code:"contact.owner.not.found")

        result.contactInstance = new Contact()
        result.contactInstance.properties = params

        // success
        return result
    }

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

        result.ownerInstance = getOwner(params)
        if(!result.ownerInstance)
            return fail(code:"contact.owner.not.found")

        result.contactInstance = new Contact(params)

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

        // success
        return result
    }

    private getOwner(Map params) {
        def ownerInstance

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

        return false
    }

    private getOwner(Object object) {
        def ownerInstance

        if(object.manufacturer)
            return ownerInstance = object.manufacturer
        if(object.supplier)
            return ownerInstance = object.supplier
        if(object.person)
            return ownerInstance = object.person
        if(object.site)
            return ownerInstance = object.site

        return false
    }

} // end of class
