'use strict';


var Immutable = require('immutable');

var AppConstants = require('../constants/AppConstants');
var Structures = require('../common/Structures');

var FamParser = require('fam-parser');


var Document = Structures.Document;
var Nest = Structures.Nest;
var Pedigree = Structures.Pedigree;
var Pregnancy = Structures.Pregnancy;
var Schema = Structures.Schema;


var accept = ['fam'];
var binary = true;


var readString = function(string) {
  var members;
  var nests;
  var parser;
  var pedigree;
  var schema;

  parser = new FamParser(string);

  members = Immutable.Map(parser.getMembers().map(member => [
    member.ID,
    Immutable.Map({
      surname: member.SURNAME,
      forenames: member.FORENAMES,
      gender: AppConstants.Gender[member.SEX]
    })
  ]));

  nests = Immutable.Map(parser.getRelationships().map(relationship => [
    Immutable.Set.of(relationship.MEMBER_1_ID, relationship.MEMBER_2_ID),
    new Nest({
      consanguineous: relationship.RELATION_IS_CONSANGUINEOUS
    })
  ]));

  parser.getMembers().forEach(member => {
    var nestKey;
    if (members.has(member.MOTHER_ID) && members.has(member.FATHER_ID)) {
      nestKey = Immutable.Set.of(member.MOTHER_ID, member.FATHER_ID);
      nests = nests.updateIn([nestKey, 'pregnancies'], pregnancies => pregnancies.push(
        new Pregnancy({zygotes: Immutable.List.of(member.ID)})
      ));
    }
  });

  pedigree = new Pedigree({
    members,
    nests,
    fields: Immutable.Map({note: 'Imported from FAM'})
  });

  schema = new Schema({
    pedigree: Immutable.fromJS({
      note: {
        title: 'Note',
        type: 'string'
      }
    }),
    member: Immutable.fromJS({
      surname: {
        title: 'Surname',
        type: 'string'
      },
      forename: {
        title: 'Forename',
        type: 'string'
      }
    })
  });

  return new Document({pedigree, schema});
};


module.exports = {accept, binary, readString};

@@ -408,24 +408,245 @@
 y = true;%0A%0A%0A
+var mapGender = function(gender) %7B%0A  if (gender === 'MALE') %7B%0A    return AppConstants.Gender.Male;%0A  %7D else if (gender === 'FEMALE') %7B%0A    return AppConstants.Gender.Female;%0A  %7D%0A  return AppConstants.Gender.Unknown;%0A%7D;%0A%0A%0A
 var readStri
@@ -958,28 +958,18 @@
 er: 
-AppConstants.
+map
 Gender
-%5B
+(
 memb
@@ -974,17 +974,17 @@
 mber.SEX
-%5D
+)
 %0A    %7D)%0A

Fix gender parsing in FAM reader