<?php
	
/**
 * @file
 * Defines the inline entity form controller for Users.
 */

class UserInlineEntityFormController extends EntityInlineEntityFormController {

  /**
  * Overrides EntityInlineEntityFormController::labels().
   */
  public function labels() {
    $labels = array(
      'singular' => t('user'),
      'plural' => t('users'),
    );
    return $labels;
  }

  /**
   * Overrides EntityInlineEntityFormController::entityForm().
   */
  public function entityForm($entity_form, &$form_state) {
    $account = $entity_form['#entity'];
    if (isset($account->uid) && $account->uid!=0) {
    	$account = user_load($account->uid,true);
    	require_once drupal_get_path('module', 'user').'/user.pages.inc';
    	$form_state['user'] = $account;
    	$entity_form  = user_profile_form($entity_form,$form_state,$account);
    	
    	$this->invokeAlterHooks('user_profile_form',$entity_form,$form_state );
    	//$entity_form['#user_category']='main';
    }else { 
    	$entity_form = user_register_form($entity_form, $form_state);
    	$this->invokeAlterHooks('user_register_form',$entity_form,$form_state );
    }
    return $entity_form;
  }
  private function invokeAlterHooks($form_id,&$entity_form,&$form_state) {
  	$hooks = array('form');
  	$hooks[] = 'form_' . $form_id;
  	drupal_alter($hooks, $entity_form, $form_state, $form_id);
  }
  public function entityFormValidate($entity_form, &$form_state) {
  	parent::entityFormValidate($entity_form, $form_state);
  	$child_form_state = $this->getFormState($form_state, $entity_form);
	user_account_form_validate($entity_form, $child_form_state);
//  	form_set_error('mail','XY');
  }
  private function getFormState($form_state,$entity_form) { 
  	$child_form_state = form_state_defaults();
  	$child_form_state['values'] = drupal_array_get_nested_value($form_state['values'], $entity_form['#parents']);
	//$child_form_state['values'] = array_merge($child_form_state['values'], $child_form_state['values']['account']);
  	
  	return $child_form_state;
  }
  /**
   * Overrides EntityInlineEntityFormController::entityFormSubmit().
   */
  public function entityFormSubmit(&$entity_form, &$form_state) {
    //parent::entityFormSubmit($entity_form, $form_state);
    $child_form_state = $this->getFormState($form_state,$entity_form);
    $account = $entity_form['#entity'];
    
    if (isset($account->uid) && $account->uid!=0) {
    	require_once drupal_get_path('module', 'user').'/user.pages.inc';
    	$child_form_state['user']=$account;
    	//$entity_form['#user_category']='main';
    	
    	user_profile_form_submit($entity_form, $child_form_state);
		    	
    }else { 
    	user_register_submit($entity_form, $child_form_state);
    }
  }
}
