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

#include "kernel.h"
#include "swis.h"

#include "toolbox.h"
#include "event.h"
#include "gadgets.h"
#include "flex.h"

#include "mystringset.h"
#include "msgtrans.h"
#include "ui.h"

static _stringset *_ssets=NULL;
static int _sset_count=0;

void stringset_add(ComponentId page,ObjectId win,ComponentId component,const s_match *options,int *dest)
{
  if (_ssets) {
    if (!flex_extend((flex_ptr)&_ssets,(_sset_count+1)*sizeof(_stringset))) {
      msgtrans_error("NoMem");
      exit(1);
    }
  } else {
    if (!flex_alloc((flex_ptr)&_ssets,sizeof(_stringset))) {
      msgtrans_error("NoMem");
      exit(1);
    }
  }

  _ssets[_sset_count].page=page;
  _ssets[_sset_count].win=win;
  _ssets[_sset_count].component=component;
  _ssets[_sset_count].options=options;
  _ssets[_sset_count].dest=dest;

  _sset_count++;
}

_kernel_oserror *stringset_set_value(ObjectId win,ComponentId c,const s_match list[],int value)
{
  return stringset_set_selected(0,win,c,msgtrans(list[value].token));
}

int stringset_string_value(char *string,const s_match list[])
{
  // convert a stringset return to a sensible number
  int i;

  for (i=0;list[i].token!=NULL;i++) {
    if (strcmp(string,msgtrans(list[i].token))==0) return list[i].value;
  }

  return -1;
}

static int stringset_valuechanged(int event_code,ToolboxEvent *event,IdBlock *id,void *handle)
{
  // update the settings based on the chosen option
  int index,v;
  StringSetValueChangedEvent *e=(StringSetValueChangedEvent *)event;

  for (index=0;index<_sset_count;index++) {
    if (id->self_id==_ssets[index].win && id->self_component==_ssets[index].component) {
      // found it
      // convert...
      v=stringset_string_value(e->string,_ssets[index].options);
      if (v!=-1) *(_ssets[index].dest)=v;
      window_set_fades(_ssets[index].page,id->self_id,(settings *)handle);
      return 1;
    }
  }
  return 0;
}


void stringset_init(settings *s)
{
  event_register_toolbox_handler(-1,StringSet_ValueChanged,stringset_valuechanged,s);
}
