

#import "Person.h"
#import "random.h"

#define numOpinions 10

@implementation Person


- createEnd
{
  int i;
  myOpinion =[[self getZone] allocBlock: numOpinions * sizeof(int)];
  for (i=0; i<numOpinions; i++)
    {
      myOpinion[i]=[uniformIntRand getIntegerWithMin:0 withMax:1];
    }

  return self;

}

- setID: (int)x
{
  idnum = x;
  return self;
}

- (int)getID
{
  return idnum;
}

- setSex: (sex) aSex
{
  mySex = aSex;
  return self;
}

- (sex)getSex
{
  return mySex;
}

- setOpinion: (int*)anOpinion
{
  myOpinion = anOpinion;
  return self;
}

- (int*)getOpinionArray
{
  return myOpinion;
}

- setOpinionIssue: (int) x To: (int) y
{
  myOpinion[x] = y;
  return self;
}

- (int)getOpinionIssue: (int)x
{
  return myOpinion[x];
}


- (int)changeOpinion: (int)x
{
  
  // printf("Change old opinion %d from: %d \n", x, myOpinion[x]);
  myOpinion[x] = (myOpinion[x]==0) ? 1 : 0;
  //printf("to new opinion %d \n", myOpinion[x]);
  return myOpinion[x];
}



- setSpouse: (Person*)aPerson
{
  mySpouse = aPerson;
  return self;
}



- (Person*)getSpouse
{
  return mySpouse;
}


- (int)considerMarrying: (Person*)aPerson
{
  int dist = [self measureDistance: aPerson];
  if (dist < 4)
    {
      //int time = getCurrentTime();
      int time = 0;
      distRecord[time]= dist;
      mySpouse = aPerson;
      spouseDist = dist;
      smallerDist = 0;
      return dist;
    }
  else
    {
    return 10;
    }
  return 99;
}

- considerStayingMarried
{
  int dist;

  if (!mySpouse)
    {
      fprintf(stderr,"I have a nil spouse and spouseDist is %d \n", spouseDist);   
    }
  else
    {
      dist = [self measureDistance: mySpouse];
      //printf("Old spouse dist %d new spouse dist %d \n", spouseDist,dist);
      if (dist < 4 )
	{
	  int time = getCurrentTime();
	  distRecord[time]= dist;
	  spouseDist = dist;
	  if (distRecord[time] < distRecord[time-1]) smallerDist = 1;
	  else smallerDist = 0;
	  return nil;
	}
      
      else
	{
	  id spouseRef = mySpouse;
	  spouseDist = 998;
	  mySpouse= nil;
	  return spouseRef;
	}
    }
  return nil;
}


- (int)measureDistance: (Person *)aPerson
{
  int i;
  int dist = 0;
  int * otherOpinion = [aPerson getOpinionArray];
  for (i = 0; i < 10; i++)
    {
      if (otherOpinion[i] != myOpinion[i])
	{
	  dist++;
	}
    }
  return dist;
}

- (int)getSpouseDistance
{
  //fprintf(stderr,"getSpouseDist %d \n",spouseDist);
  return spouseDist;

}


- (int)getDistAt: (int) x
{
  //fprintf(stderr,"getSpouseDistRecord time %d= %d \n",x,distRecord[x]);
  return distRecord[x];
}

- (int)getSmallerDist
{
  return smallerDist;
}

@end
