/*
 * Copyright 2008-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.broadleafcommerce.admin.server.service.handler;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.broadleafcommerce.common.exception.ServiceException;
import org.broadleafcommerce.core.catalog.domain.Product;
import org.broadleafcommerce.openadmin.client.dto.Entity;
import org.broadleafcommerce.openadmin.client.dto.FieldMetadata;
import org.broadleafcommerce.openadmin.client.dto.PersistencePackage;
import org.broadleafcommerce.openadmin.client.dto.PersistencePerspective;
import org.broadleafcommerce.openadmin.server.dao.DynamicEntityDao;
import org.broadleafcommerce.openadmin.server.service.handler.CustomPersistenceHandlerAdapter;
import org.broadleafcommerce.openadmin.server.service.persistence.module.RecordHelper;

import java.util.Map;

/**
 * @author Jeff Fischer
 */
public class ProductCustomPersistenceHandler extends CustomPersistenceHandlerAdapter {

    private static final Log LOG = LogFactory.getLog(ProductCustomPersistenceHandler.class);

    @Override
    public Boolean canHandleAdd(PersistencePackage persistencePackage) {
        String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname();
        String[] customCriteria = persistencePackage.getCustomCriteria();
        return !ArrayUtils.isEmpty(customCriteria) && "productDirectEdit".equals(customCriteria[0]) && Product.class.getName().equals(ceilingEntityFullyQualifiedClassname);
    }

    @Override
    public Boolean canHandleUpdate(PersistencePackage persistencePackage) {
        return canHandleAdd(persistencePackage);
    }

    @Override
    public Entity add(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {
        Entity entity  = persistencePackage.getEntity();
		try {
			PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
			Product adminInstance = (Product) Class.forName(entity.getType()[0]).newInstance();
			Map<String, FieldMetadata> adminProperties = helper.getSimpleMergedProperties(Product.class.getName(), persistencePerspective);
			adminInstance = (Product) helper.createPopulatedInstance(adminInstance, entity, adminProperties, false);

            if (adminInstance.getDefaultCategory() != null && !adminInstance.getAllParentCategories().contains(adminInstance.getDefaultCategory())) {
                adminInstance.getAllParentCategories().add(adminInstance.getDefaultCategory());
            }

			adminInstance = (Product) dynamicEntityDao.merge(adminInstance);

			return helper.getRecord(adminProperties, adminInstance, null, null);
		} catch (Exception e) {
            LOG.error("Unable to add entity for " + entity.getType()[0], e);
			throw new ServiceException("Unable to add entity for " + entity.getType()[0], e);
		}
    }

    @Override
    public Entity update(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {
        Entity entity = persistencePackage.getEntity();
		try {
			PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
			Map<String, FieldMetadata> adminProperties = helper.getSimpleMergedProperties(Product.class.getName(), persistencePerspective);
			Object primaryKey = helper.getPrimaryKey(entity, adminProperties);
            Product adminInstance = (Product) dynamicEntityDao.retrieve(Class.forName(entity.getType()[0]), primaryKey);
			adminInstance = (Product) helper.createPopulatedInstance(adminInstance, entity, adminProperties, false);

            if (adminInstance.getDefaultCategory() != null && !adminInstance.getAllParentCategories().contains(adminInstance.getDefaultCategory())) {
                adminInstance.getAllParentCategories().add(adminInstance.getDefaultCategory());
            }

            adminInstance = (Product) dynamicEntityDao.merge(adminInstance);

			return helper.getRecord(adminProperties, adminInstance, null, null);
		} catch (Exception e) {
            LOG.error("Unable to update entity for " + entity.getType()[0], e);
			throw new ServiceException("Unable to update entity for " + entity.getType()[0], e);
		}
    }
}

@@ -927,16 +927,136 @@
 roduct;%0A
+import org.broadleafcommerce.core.catalog.domain.Sku;%0Aimport org.broadleafcommerce.core.catalog.service.CatalogService;%0A
 import o
@@ -1561,24 +1561,59 @@
 ordHelper;%0A%0A
+import javax.annotation.Resource;%0A%0A
 import java.
@@ -1741,16 +1741,107 @@
 dapter %7B
+%0A    %0A    @Resource(name = %22blCatalogService%22)%0A    protected CatalogService catalogService;
 %0A%0A    pr
@@ -3500,36 +3500,663 @@
 adminInstance);%0A
-%0A%09%09%09
+            %0A%09%09%09//Since none of the Sku fields are required, it's possible that the user did not fill out%0A%09%09%09//any Sku fields, and thus a Sku would not be created. Product still needs a default Sku so instantiate one%0A%09%09%09if (adminInstance.getDefaultSku() == null) %7B%0A%09%09%09    Sku newSku = catalogService.createSku();%0A%09%09%09    adminInstance.setDefaultSku(newSku);%0A%09%09%09    adminInstance = (Product) dynamicEntityDao.merge(adminInstance);%0A%09%09%09%7D%0A%0A%09%09%09//also set the default product for the Sku%0A%09%09%09adminInstance.getDefaultSku().setDefaultProduct(adminInstance);%0A            dynamicEntityDao.merge(adminInstance.getDefaultSku());%0A%09%09%09%0A            
 return helper.ge
@@ -5499,16 +5499,28 @@
 tance);%0A
+            
 %0A%09%09%09retu

Change the Product persistence handler to deal with the changed mappings between Product and Sku