// AppProfileDelete delete the app
func (ac *APIController) AppProfileDelete(prof *contivModel.AppProfile) error {
	log.Infof("Received AppProfileDelete: %+v", prof)

	tenant := contivModel.FindTenant(prof.TenantName)
	if tenant == nil {
		return core.Errorf("Tenant %s not found", prof.TenantName)
	}

	DeleteAppNw(prof)

	// remove all links
	for _, epg := range prof.EndpointGroups {
		epgKey := prof.TenantName + ":" + epg
		epgObj := contivModel.FindEndpointGroup(epgKey)
		if epgObj == nil {
			log.Errorf("EndpointGroup %s not found", epgKey)
			continue
		}
		modeldb.RemoveLink(&epgObj.Links.AppProfile, prof)
		err := epgObj.Write()
		if err != nil {
			log.Errorf("Error updating epg state(%+v). Err: %v", epgObj, err)
		}
	}

	modeldb.RemoveLinkSet(&tenant.LinkSets.AppProfiles, prof)
	tenant.Write()
	return nil
}
// AppProfileUpdate updates app
func (ac *APIController) AppProfileUpdate(oldProf, newProf *contivModel.AppProfile) error {
	log.Infof("Received AppProfileUpdate: %+v, newProf: %+v", oldProf, newProf)

	// handle any epg addition
	for _, epg := range newProf.EndpointGroups {
		epgKey := newProf.TenantName + ":" + epg
		log.Infof("Add %s to %s", epgKey, newProf.AppProfileName)
		epgObj := contivModel.FindEndpointGroup(epgKey)
		if epgObj == nil {
			return core.Errorf("EndpointGroup %s not found", epgKey)
		}
		modeldb.AddLinkSet(&newProf.LinkSets.EndpointGroups, epgObj)

		// workaround for objdb update problem
		modeldb.AddLinkSet(&oldProf.LinkSets.EndpointGroups, epgObj)

		modeldb.AddLink(&epgObj.Links.AppProfile, newProf)
		err := epgObj.Write()
		if err != nil {
			log.Errorf("Error updating epg state(%+v). Err: %v", epgObj, err)
			return err
		}
	}

	// handle any epg removal
	for _, epg := range oldProf.EndpointGroups {
		if !stringInSlice(epg, newProf.EndpointGroups) {
			epgKey := newProf.TenantName + ":" + epg
			log.Infof("Remove %s from %s", epgKey, newProf.AppProfileName)
			epgObj := contivModel.FindEndpointGroup(epgKey)
			if epgObj == nil {
				return core.Errorf("EndpointGroup %s not found", epgKey)
			}
			modeldb.RemoveLink(&epgObj.Links.AppProfile, oldProf)
			err := epgObj.Write()
			if err != nil {
				log.Errorf("Error updating epg state(%+v). Err: %v",
					epgObj, err)
				return err
			}

			// workaround for objdb update problem
			modeldb.RemoveLinkSet(&oldProf.LinkSets.EndpointGroups, epgObj)
		}
	}

	// workaround for objdb update problem -- should fix model
	oldProf.EndpointGroups = newProf.EndpointGroups

	// update the app nw
	DeleteAppNw(oldProf)
	CreateAppNw(oldProf)
	return nil
}