#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//
#include "proto.h"
#include "bucket.h"
#include "main.h"
#include "flash.h"
#include "action.h"


S32 action_write(ACTION *actions, U32 entries) {

  U32 ptr;

  if (entries == 0)                               return 0;

  if (flush_bucket())                             return 1;
  ptr = read_position(NULL);
  if (write_ushort(0))                            return 1;

  if (action_write_list(actions, entries))        return 1;
  return update_record_header(stagDoAction, ptr);
}



S32 action_write_list(ACTION *actions, U32 n) {

  U32 i;

  for (i = 0; i < n; i++) {
    if (write_ubyte(actions[i].action))                               return 1;
    switch (actions[i].action) {
    case ACTION_GOTOFRAME:
      if (write_ushort(2))                                            return 1;
      if (write_ushort(actions[i].data.gotoframe))                    return 1;
      break;
    case ACTION_GETURL:
      {
        U32 c;
        if (write_ushort(strlen(actions[i].data.geturl.url)+1+
                         strlen(actions[i].data.geturl.target)+1))    return 1;
        c = 0;
        while (actions[i].data.geturl.url[c])
          if (write_ubyte(actions[i].data.geturl.url[c++]))           return 1;
        if (write_ubyte(0))                                           return 1;
        c = 0;
        while (actions[i].data.geturl.target[c])
          if (write_ubyte(actions[i].data.geturl.target[c++]))        return 1;
        if (write_ubyte(0))                                           return 1;
      }
      break;
    case ACTION_PLAY:
    case ACTION_NEXTFRAME:
    case ACTION_PREVIOUSFRAME:
    case ACTION_STOP:
    case ACTION_STOPSOUNDS:
      break;
    default:
      return 1;
      break;
    }
  }

  if (write_ubyte(ACTION_NULL))                   return 1;

  return 0;
}


S32 add_action(ACTION **list, U32 *count, ACTION *newaction) {

  if (!*list) {
    *list = malloc(sizeof(ACTION));
    if (!*list)                          return 1;
  } else {
    ACTION *newlist;
    newlist = realloc(*list, (*count+1)*sizeof(ACTION));
    if (!newlist)                       return 1;
    *list = newlist;
  }

  memcpy(*list+*count, newaction, sizeof(ACTION));
  *count = *count+1;

  return 0;
}
