<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:dw="http://www.mulesoft.org/schema/mule/ee/dw"
	xmlns:db="http://www.mulesoft.org/schema/mule/db" xmlns:core="http://www.mulesoft.org/schema/mule/core"
	xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking" xmlns="http://www.mulesoft.org/schema/mule/core"
	xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
	xmlns:batch="http://www.mulesoft.org/schema/mule/batch" xmlns:sfdc="http://www.mulesoft.org/schema/mule/sfdc"
	xmlns:smtp="http://www.mulesoft.org/schema/mule/smtp" xmlns:json="http://www.mulesoft.org/schema/mule/json"
	xmlns:spring="http://www.springframework.org/schema/beans" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/batch http://www.mulesoft.org/schema/mule/batch/current/mule-batch.xsd
http://www.mulesoft.org/schema/mule/ee/tracking http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd
http://www.mulesoft.org/schema/mule/sfdc http://www.mulesoft.org/schema/mule/sfdc/current/mule-sfdc.xsd
http://www.mulesoft.org/schema/mule/smtp http://www.mulesoft.org/schema/mule/smtp/current/mule-smtp.xsd
http://www.mulesoft.org/schema/mule/db http://www.mulesoft.org/schema/mule/db/current/mule-db.xsd
http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd">

    <batch:job name="syncContactBatch">
        <batch:threading-profile poolExhaustedAction="WAIT"/>
        <batch:input>
	        <db:select config-ref="Database" doc:name="Query Contact from Database">
                <db:parameterized-query><![CDATA[SELECT ID,AccountName,FirstName,LastName,Phone,SalesforceId,LastModifiedById,Name,Email FROM contact;]]></db:parameterized-query>


	
	        </db:select>
        </batch:input>
        <batch:process-records>
            <batch:step name="getContactInSalesforceStep">
                <enricher source="#[payload == null ? null : payload.Id]" target="#[payload.Id]" doc:name="set payload Id with SFDC contact Id if exists">
                    <sfdc:query-single config-ref="Salesforce" query="SELECT Id FROM Contact WHERE Name = '#[payload[&quot;Name&quot;]]'" doc:name="Query Salesforce for Contact"/>
                </enricher>
            </batch:step>
            <batch:step name="findOrCreateAccountInSalesforceStep" accept-expression="#['syncAccount' == '${account.sync.policy}' &amp;&amp; payload.AccountName != null]">
            
                      <enricher source="#[payload == null ? null : payload.Id]" target="#[payload.AccountId]" doc:name="enrich payload with existing AccountId">
                          <sfdc:query-single config-ref="Salesforce" query="SELECT Id FROM Account WHERE Name = '#[payload['AccountName']]'" doc:name="Query Account in Salesforce Instance"/>
                      </enricher>
                <choice doc:name="Should be a new Account created?">
                    <when expression="#[payload.AccountId == null]">
                        <enricher source="#[payload.getId()]" target="#[payload.AccountId]" doc:name="enrich payload with new AccountId">
                            <sfdc:create-single config-ref="Salesforce" type="Account" doc:name="Create Account in Salesforce">
                                <sfdc:object>
                                    <sfdc:object key="Name">#[payload['AccountName']]</sfdc:object>
                                </sfdc:object>
                            </sfdc:create-single>
                        </enricher>
                    </when>
                    <otherwise>
                        <logger level="INFO" doc:name="Existing Account Id already set"/>
                    </otherwise>
                </choice>
            
            </batch:step>
            
            <batch:step name="upsertContactInSalesforceStep">

                <batch:commit size="${page.size}" doc:name="Batch Commit">
                    <dw:transform-message doc:name="DB Contact to SFDC Contact">
                        <dw:set-payload><![CDATA[%dw 1.0
%output application/java
---
payload map {
	(Id: $.Id) when $.Id != null,
	(AccountId: $.AccountId) when $.AccountId?,
	FirstName: $.FirstName,
	LastName: $.LastName,
	Email: $.Email,
	Phone: $.Phone
}]]></dw:set-payload>
                    </dw:transform-message>
                    <sfdc:upsert config-ref="Salesforce" externalIdFieldName="Id" type="Contact" doc:name="Upsert Contact in Salesforce">
                        <sfdc:objects ref="#[payload]"/>
                    </sfdc:upsert>
                    <logger message="Upserted Contact #[payload]" level="INFO" doc:name="Log result"/>
                </batch:commit>
            </batch:step>
        </batch:process-records>
        <batch:on-complete>
            <scatter-gather doc:name="All">
                <processor-chain>
                    <json:object-to-json-transformer doc:name="Transform BatchJobInstance to JSON"/>
                    <logger message="Migration process has finished: #[payload]" level="INFO" doc:name="Log migration process has finished"/>
                </processor-chain>
                <processor-chain>
                    <parse-template location="email/body.html" doc:name="Parse Template" />
                    <smtp:outbound-endpoint host="${smtp.host}" port="${smtp.port}" user="${smtp.user}" password="${smtp.password}" to="${mail.to}" from="${mail.from}" subject="${mail.subject}" responseTimeout="10000" connector-ref="gmailConnector" doc:name="Send result of the batch in mail"/>
                </processor-chain>
            </scatter-gather>

        </batch:on-complete>
    </batch:job>

</mule>
