/*
 * addritem.c:
 *
 * See the README file for copyright information and how to reach the author.
 *
 * $Id: addritem.c,v 1.1.1.1 2005/06/27 13:37:56 cm Exp $
 */

#include "addritem.h"

// --- cMenuEditAddrItem -------------------------------------------------------

cMenuEditAddrItem::cMenuEditAddrItem(const char *Name, unsigned long *Value) : cMenuEditItem(Name) {
  p_value = Value;
  num = 0;
  pos = -1;
  lock = false;

  Set();
}

cMenuEditAddrItem::~cMenuEditAddrItem() {
}

void cMenuEditAddrItem::Set(void) {
  char *p_buff = NULL;

  asprintf(&p_buff, "%s%u%s.%s%u%s.%s%u%s.%s%u%s", 
           3 == pos ? "[" : "", (unsigned char)((*p_value & 0xFF000000) >> 24), 3 == pos ? "]" : "",
           2 == pos ? "[" : "", (unsigned char)((*p_value & 0x00FF0000) >> 16), 2 == pos ? "]" : "",
           1 == pos ? "[" : "", (unsigned char)((*p_value & 0x0000FF00) >> 8), 1 == pos ? "]" : "",
           0 == pos ? "[" : "", (unsigned char)*p_value & 0x000000FF, 0 == pos ? "]" : "");

  SetValue(p_buff);
  free(p_buff);
}

eOSState cMenuEditAddrItem::ProcessKey(eKeys Key) {
  unsigned long mask = 0xFF;
  eOSState state = lock ? osContinue : osUnknown;

  num = (unsigned char)(*p_value >> (pos * 8));

  switch (Key) {
    case kUp:
    case kUp | k_Repeat:
      if (lock && 255 > num) {
        num++;
        *p_value &= ~(mask << (pos * 8));
        *p_value |= ((unsigned long)num << (pos * 8));
        mask = 0xFF;
      }
      break;
    case kDown:
    case kDown | k_Repeat:
      if (lock && 0 < num) {
        num--;
        *p_value &= ~(mask << (pos * 8));
        *p_value |= ((unsigned long)num << (pos * 8));
      }
      break;
    case kLeft:
    case kLeft | k_Repeat:
      if (lock && 3 > pos) {
        pos++;
        num = (int)((*p_value & (mask << (pos * 8))) >> (pos * 8));
      }
      break;
    case kRight:
    case kRight | k_Repeat:
      if (lock) {
        if (0 < pos) {
          pos--;
          num = (unsigned char)((*p_value & (mask << (pos * 8))) >> (pos * 8));
        }
      } else {
        lock = true;
        pos = 3;
        state = osContinue;
      }
      break;
    case kOk:
      lock = false;
      pos = -1;
      break;
    case k0 ... k9:
      break;
    default:
      state = cMenuEditItem::ProcessKey(Key);
  }

  Set();

  return state;
}
