#include "friends.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

/*
 * Create a new user with the given name.  Insert it at the tail of the list
 * of users whose head is pointed to by *user_ptr_add.
 *
 * Return:
 *   - 0 if successful
 *   - 1 if a user by this name already exists in this list
 *   - 2 if the given name cannot fit in the 'name' array
 *       (don't forget about the null terminator)
 */
int create_user(const char *name, User **user_ptr_add) {
  // check to see if name fits into name array.
  if (strlen(name) + 1 > MAX_NAME) {
    return 2;
  }

  User *new_user = malloc(sizeof(struct user));

  if (new_user == NULL) {
    return 3; // malloc failed.
  }

  strncpy(new_user->name, name, MAX_NAME);

  // initailie all values of friends array to null. Usefull for make_friends
  // function.
  for (int i = 0; i < MAX_FRIENDS; i++) {
    new_user->friends[i] = NULL;
  }

  new_user->next = NULL;
	new_user->first_post = NULL;
	
  // if linked list is empty
  if (*user_ptr_add == NULL) {
    *user_ptr_add = new_user;
    return 0;
  }

  User *curr = *user_ptr_add;

  // traverse through the linked list, checking if the name is already taken.
  while (curr->next != NULL) {
    if (strcmp(name, curr->name) == 0) {
      free(new_user);
      return 1;
    }
    curr = curr->next;
  }

  curr->next = new_user;

  return 0;
}

/*
 * Create a new user with the given name.  Insert it at the tail of the list
 * of users whose head is pointed to by *user_ptr_add.
 *
 * Return:
 *   - 0 if successful
 *   - 1 if a user by this name already exists in this list
 *   - 2 if the given name cannot fit in the 'name' array
 *       (don't forget about the null terminator)
 */

