// EndpointGroupDelete deletes end point group
func (ac *APIController) EndpointGroupDelete(endpointGroup *contivModel.EndpointGroup) error {
	log.Infof("Received EndpointGroupDelete: %+v", endpointGroup)

	// delete the endpoint group state
	err := master.DeleteEndpointGroup(endpointGroup.EndpointGroupID)
	if err != nil {
		log.Errorf("Error creating endpoing group %+v. Err: %v", endpointGroup, err)
	}

	// Detach the endpoint group from the Policies
	for _, policyName := range endpointGroup.Policies {
		policyKey := endpointGroup.TenantName + ":" + policyName

		// find the policy
		policy := contivModel.FindPolicy(policyKey)
		if policy == nil {
			log.Errorf("Could not find policy %s", policyName)
			continue
		}

		// detach policy to epg
		err := master.PolicyDetach(endpointGroup, policy)
		if err != nil && err != master.EpgPolicyExists {
			log.Errorf("Error detaching policy %s from epg %s", policyName, endpointGroup.Key)
		}

		// Remove links
		modeldb.RemoveLinkSet(&policy.LinkSets.EndpointGroups, endpointGroup)
		modeldb.RemoveLinkSet(&endpointGroup.LinkSets.Policies, policy)
		policy.Write()
	}

	return nil
}
// Cleans up state off endpointGroup and related objects.
func endpointGroupCleanup(endpointGroup *contivModel.EndpointGroup) {
	// delete the endpoint group state
	err := master.DeleteEndpointGroup(endpointGroup.TenantName, endpointGroup.GroupName)
	if err != nil {
		log.Errorf("Error deleting endpoint group %+v. Err: %v", endpointGroup, err)
	}

	// Detach the endpoint group from the Policies
	for _, policyName := range endpointGroup.Policies {
		policyKey := endpointGroup.TenantName + ":" + policyName

		// find the policy
		policy := contivModel.FindPolicy(policyKey)
		if policy == nil {
			log.Errorf("Could not find policy %s", policyName)
			continue
		}

		// detach policy to epg
		err := master.PolicyDetach(endpointGroup, policy)
		if err != nil && err != master.EpgPolicyExists {
			log.Errorf("Error detaching policy %s from epg %s", policyName, endpointGroup.Key)
		}

		// Remove links
		modeldb.RemoveLinkSet(&policy.LinkSets.EndpointGroups, endpointGroup)
		modeldb.RemoveLinkSet(&endpointGroup.LinkSets.Policies, policy)
		policy.Write()
	}

	// Cleanup any external contracts
	err = cleanupExternalContracts(endpointGroup)
	if err != nil {
		log.Errorf("Error cleaning up external contracts for epg %s", endpointGroup.Key)
	}

	// Remove the endpoint group from network and tenant link sets.
	nwObjKey := endpointGroup.TenantName + ":" + endpointGroup.NetworkName
	network := contivModel.FindNetwork(nwObjKey)
	if network != nil {
		modeldb.RemoveLinkSet(&network.LinkSets.EndpointGroups, endpointGroup)
		network.Write()
	}
	tenant := contivModel.FindTenant(endpointGroup.TenantName)
	if tenant != nil {
		modeldb.RemoveLinkSet(&tenant.LinkSets.EndpointGroups, endpointGroup)
		tenant.Write()
	}
}
// EndpointGroupUpdate updates endpoint group
func (ac *APIController) EndpointGroupUpdate(endpointGroup, params *contivModel.EndpointGroup) error {
	log.Infof("Received EndpointGroupUpdate: %+v, params: %+v", endpointGroup, params)

	// Only update policy attachments

	// Look for policy adds
	for _, policyName := range params.Policies {
		if !stringInSlice(policyName, endpointGroup.Policies) {
			policyKey := endpointGroup.TenantName + ":" + policyName

			// find the policy
			policy := contivModel.FindPolicy(policyKey)
			if policy == nil {
				log.Errorf("Could not find policy %s", policyName)
				return core.Errorf("Policy not found")
			}

			// attach policy to epg
			err := master.PolicyAttach(endpointGroup, policy)
			if err != nil && err != master.EpgPolicyExists {
				log.Errorf("Error attaching policy %s to epg %s", policyName, endpointGroup.Key)
				return err
			}

			// Setup links
			modeldb.AddLinkSet(&policy.LinkSets.EndpointGroups, endpointGroup)
			modeldb.AddLinkSet(&endpointGroup.LinkSets.Policies, policy)
			err = policy.Write()
			if err != nil {
				return err
			}
		}
	}

	// now look for policy removals
	for _, policyName := range endpointGroup.Policies {
		if !stringInSlice(policyName, params.Policies) {
			policyKey := endpointGroup.TenantName + ":" + policyName

			// find the policy
			policy := contivModel.FindPolicy(policyKey)
			if policy == nil {
				log.Errorf("Could not find policy %s", policyName)
				return core.Errorf("Policy not found")
			}

			// detach policy to epg
			err := master.PolicyDetach(endpointGroup, policy)
			if err != nil && err != master.EpgPolicyExists {
				log.Errorf("Error detaching policy %s from epg %s", policyName, endpointGroup.Key)
				return err
			}

			// Remove links
			modeldb.RemoveLinkSet(&policy.LinkSets.EndpointGroups, endpointGroup)
			modeldb.RemoveLinkSet(&endpointGroup.LinkSets.Policies, policy)
			err = policy.Write()
			if err != nil {
				return err
			}
		}
	}

	// Update the policy list
	endpointGroup.Policies = params.Policies

	return nil
}
// EndpointGroupUpdate updates endpoint group
func (ac *APIController) EndpointGroupUpdate(endpointGroup, params *contivModel.EndpointGroup) error {
	log.Infof("Received EndpointGroupUpdate: %+v, params: %+v", endpointGroup, params)

	// if the network association was changed, reject the update.
	if endpointGroup.NetworkName != params.NetworkName {
		return core.Errorf("Cannot change network association after epg is created.")
	}

	// Only update policy attachments

	// Look for policy adds
	for _, policyName := range params.Policies {
		if !stringInSlice(policyName, endpointGroup.Policies) {
			policyKey := endpointGroup.TenantName + ":" + policyName

			// find the policy
			policy := contivModel.FindPolicy(policyKey)
			if policy == nil {
				log.Errorf("Could not find policy %s", policyName)
				return core.Errorf("Policy not found")
			}

			// attach policy to epg
			err := master.PolicyAttach(endpointGroup, policy)
			if err != nil && err != master.EpgPolicyExists {
				log.Errorf("Error attaching policy %s to epg %s", policyName, endpointGroup.Key)
				return err
			}

			// Setup links
			modeldb.AddLinkSet(&policy.LinkSets.EndpointGroups, endpointGroup)
			modeldb.AddLinkSet(&endpointGroup.LinkSets.Policies, policy)
			err = policy.Write()
			if err != nil {
				return err
			}
		}
	}

	// now look for policy removals
	for _, policyName := range endpointGroup.Policies {
		if !stringInSlice(policyName, params.Policies) {
			policyKey := endpointGroup.TenantName + ":" + policyName

			// find the policy
			policy := contivModel.FindPolicy(policyKey)
			if policy == nil {
				log.Errorf("Could not find policy %s", policyName)
				return core.Errorf("Policy not found")
			}

			// detach policy to epg
			err := master.PolicyDetach(endpointGroup, policy)
			if err != nil && err != master.EpgPolicyExists {
				log.Errorf("Error detaching policy %s from epg %s", policyName, endpointGroup.Key)
				return err
			}

			// Remove links
			modeldb.RemoveLinkSet(&policy.LinkSets.EndpointGroups, endpointGroup)
			modeldb.RemoveLinkSet(&endpointGroup.LinkSets.Policies, policy)
			err = policy.Write()
			if err != nil {
				return err
			}
		}
	}
	// Update the policy list
	endpointGroup.Policies = params.Policies

	// For the external contracts, we can keep the update simple. Remove
	// all that we have now, and update the epg with the new list.
	// Step 1: Cleanup existing external contracts.
	err := cleanupExternalContracts(endpointGroup)
	if err != nil {
		return err
	}
	// Step 2: Add contracts from the update.
	// Consumed contracts
	err = setupExternalContracts(endpointGroup, params.ExtContractsGrps)
	if err != nil {
		return err
	}

	// Update the epg itself with the new contracts groups.
	endpointGroup.ExtContractsGrps = params.ExtContractsGrps

	// if there is an associated app profiles, update that as well
	profKey := endpointGroup.Links.AppProfile.ObjKey
	profObj := contivModel.FindAppProfile(profKey)
	if profObj == nil {
		log.Warnf("EndpointGroupUpdate prof %s not found", profKey)
	} else {
		log.Infof("EndpointGroupUpdate sync prof %s", profKey)
		DeleteAppNw(profObj)
		CreateAppNw(profObj)
	}

	return nil
}