package org.hisp.dhis.dxf2.metadata.objectbundle.hooks;

/*
 * Copyright (c) 2004-2016, University of Oslo
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * Neither the name of the HISP project nor the names of its contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import org.hibernate.Session;
import org.hisp.dhis.attribute.Attribute;
import org.hisp.dhis.attribute.AttributeValue;
import org.hisp.dhis.common.BaseIdentifiableObject;
import org.hisp.dhis.common.IdentifiableObject;
import org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundle;
import org.hisp.dhis.schema.Schema;
import org.hisp.dhis.user.UserGroup;
import org.hisp.dhis.user.UserGroupAccess;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

/**
 * @author Morten Olav Hansen <mortenoh@gmail.com>
 */
@Order( 0 )
public class IdentifiableObjectBundleHook extends AbstractObjectBundleHook
{
    @Override
    public void preCreate( IdentifiableObject identifiableObject, ObjectBundle bundle )
    {
        ((BaseIdentifiableObject) identifiableObject).setAutoFields();

        Schema schema = schemaService.getDynamicSchema( identifiableObject.getClass() );
        Session session = sessionFactory.getCurrentSession();
        handleAttributeValues( session, identifiableObject, bundle, schema );
        handleUserGroupAccesses( session, identifiableObject, bundle, schema );
        handleObjectTranslations( session, identifiableObject, bundle, schema );
    }

    @Override
    public void preUpdate( IdentifiableObject object, IdentifiableObject persistedObject, ObjectBundle bundle )
    {
        ((BaseIdentifiableObject) object).setAutoFields();

        Schema schema = schemaService.getDynamicSchema( object.getClass() );
        Session session = sessionFactory.getCurrentSession();
        handleAttributeValues( session, object, bundle, schema );
        handleUserGroupAccesses( session, object, bundle, schema );
        handleObjectTranslations( session, object, bundle, schema );
    }

    private void handleAttributeValues( Session session, IdentifiableObject identifiableObject, ObjectBundle bundle, Schema schema )
    {
        if ( !schema.havePersistedProperty( "attributeValues" ) ) return;

        for ( AttributeValue attributeValue : identifiableObject.getAttributeValues() )
        {
            // if value null or empty, just skip it
            if ( StringUtils.isEmpty( attributeValue.getValue() ) ) continue;

            Attribute attribute = bundle.getPreheat().get( bundle.getPreheatIdentifier(), attributeValue.getAttribute() );
            attributeValue.setAttribute( attribute );
            session.save( attributeValue );
        }
    }

    private void handleUserGroupAccesses( Session session, IdentifiableObject identifiableObject, ObjectBundle bundle, Schema schema )
    {
        if ( !schema.havePersistedProperty( "userGroupAccesses" ) ) return;

        if ( bundle.isSkipSharing() )
        {
            identifiableObject.getUserGroupAccesses().clear();
            return;
        }

        for ( UserGroupAccess userGroupAccess : identifiableObject.getUserGroupAccesses() )
        {
            UserGroup userGroup = bundle.getPreheat().get( bundle.getPreheatIdentifier(), userGroupAccess.getUserGroup() );
            userGroupAccess.setUserGroup( userGroup );
            session.save( userGroupAccess );
        }
    }

    private void handleObjectTranslations( Session session, IdentifiableObject identifiableObject, ObjectBundle bundle, Schema schema )
    {
        if ( !schema.havePersistedProperty( "translations" ) ) return;
        identifiableObject.getTranslations().forEach( session::save );
    }
}

@@ -2101,16 +2101,44 @@
 Utils;%0A%0A
+import java.util.Iterator;%0A%0A
 /**%0A * @
@@ -4444,22 +4444,25 @@
         
-for ( 
+Iterator%3C
 UserGrou
@@ -4468,16 +4468,17 @@
 upAccess
+%3E
  userGro
@@ -4485,18 +4485,26 @@
 upAccess
- :
+Iterator =
  identif
@@ -4533,36 +4533,177 @@
 upAccesses()
- )%0A        %7B
+.iterator();%0A%0A        while ( userGroupAccessIterator.hasNext() )%0A        %7B%0A            UserGroupAccess userGroupAccess = userGroupAccessIterator.next();
 %0A           
@@ -4811,24 +4811,80 @@
 rGroup() );%0A
+%0A            if ( userGroup != null )%0A            %7B%0A    
             
@@ -4930,32 +4930,36 @@
  );%0A            
+    
 session.save( us
@@ -4971,24 +4971,133 @@
 upAccess );%0A
+            %7D%0A            else%0A            %7B%0A                userGroupAccessIterator.remove();%0A            %7D%0A
         %7D%0A  

verify UA/UGA on import, remove if user/userGroup is invalid