<?php


function materio_personalnotes_createeditnote($action = 'create', $src_nid = null, $note_nid = null){
  $debug = false;

  global $user;

  $rep = array();

  if(!$src_nid)
    drupal_json_output(array('error'=>"src_nid arguments needed"));

  $contenttype = 'note';

  // check if request is ajax, if not rediret
  if (!$debug && (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')) {
    switch ($action) {
      case 'edit':
        drupal_goto('node/'.$src_nid.'/edit');
        break;
      default:
        drupal_goto('node/add/' . $contenttype . '?target_id='.$src_nid);
        break;
    }
    exit ;
  }


  module_load_include('inc', 'node', 'node.pages');
  switch ($action) {
    case 'edit':
      if(!$note_nid){
        return "For edit action, note_nid is needed";
      }else{
        $note = node_load($note_nid);
        $form = drupal_get_form('note_node_form', $note);
      }
      break;
    default: // create
      $new_note = (object) array(
        'uid' => $user->uid,
        'name' => (isset($user->name) ? $user->name : ''),
        'type' => 'note',
        'language' => LANGUAGE_NONE,
        'field_target_content_nid' => array(
          'und'=>array(
            array(
              'value'=>$src_nid
            )
          )
        ),
        'field_personal_note' => array(
          'und'=>array(
            array(
              'value'=>""
            )
          )
        )
      );
      node_object_prepare($new_note);
      node_save($new_note);
      $note_nid = $new_note->nid;
      $rep['new_note_nid'] = $note_nid;

      $form = drupal_get_form('note_node_form', $new_note);
      // pre-fill the field_target_content_nid with src_nid argument
      // $form['field_target_content_nid']['und'][0]['value']['#default_value'] = $src_id;
      // $form['field_target_content_nid']['und'][0]['value']['#type'] = 'hidden';
      break;
  }

  $form['note_nid'] = array(
    '#type'=>'hidden',
    '#value'=> $note_nid,
    '#name' => 'note_nid',
  );

	$rendered_form = drupal_render($form);

  $rep += array(
		// 'form'=>$form,
    'rendered_form'=>$rendered_form
  );

  if ($debug) {
    dsm($rep, 'rep');
    return "debug display";
  }else{
    drupal_json_output($rep);
  }
}


function materio_personalnotes_savenote($note_nid = null){
  $debug = false;

  if(!$note_nid)
    drupal_json_output(array('error'=>"note_nid arguments needed"));

  $node = node_load($note_nid);
  // $note->field_target_content_nid
  $node->field_personal_note[$node->language][0]['value'] = $_POST['content'];
  node_save($node);

  if($debug){
    dsm($node, "note node");
    return 'debug display';
  }else{
    drupal_json_output(array('status'=>'note node saved'));
  }
}
