Code coverage report for api/Collection.js

Statements: 76.16% (409 / 537)      Branches: 74.38% (331 / 445)      Functions: 72.84% (59 / 81)      Lines: 76.16% (409 / 537)      Ignored: none     

All files » api/ » Collection.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245    1 1                       1 19577 87   19577 19577 6783     19577 11852                 19577 14117 12003   2114   19577         19577 12734   19577 19577     1   1             135971                                 1338284 1338284                                   1338284                                                           12                   62         7         3                     7           4676391 15379   4676391     12734 731   12003 3467 3467   8536         8536 122576 122576     122576     8536                                                                           3070         3070 557 557 2513 2512     3070   3070 1     3069 7 7 7     3069   1838 2     1836 1836 1038 798   798     1836 1836       3067 724   3067 40 40 40     3067   3023 3023   3023   3067 3067 39757   1290 577   1290 38467           3067   3067 3 3 9 1 1 1       3067             3           133745   133745 133727     133745     133742 133742 133742   133742                     7682 7682 7616     7682                   126060   133742 133742 3 3     133739       133742 169 169     133573       133573 2074516     2074516 2     2     2 2 2             2       133571 133571   133571 133565             133571 133571     133571 68   133503   133571             75436 75436                 17742 17742     99 99 99                             134009         134009 134009 3 3 3   134006 134000   134006 134006 134006 4771   134006                       134298 29 126   29     134269           5 1   4 1   3 3             11           7           4     4 4     4 4       4 4 4   4 4 4 4   4           1     1 1     1 1       1 1 1   1 1 1 1   1           259     259           259 257     259 261     259 259 2 2         257 262       262 262       262 261 261   262 262 12 12               257 1769 262 262   262 262 13 13 15 8     13 5 5             257     257 257 257           330     330 2165 2165 281 281 258   23   258   2142 306       1           1     1           17 2   17           17                                                                         1       1 1   1 1 1 1           1   1 1   1 1 1                                       1           13013   13013 142680 142680 142680           13013                   24 24 234 234 234           24           24 24 24           2 2 2 2                                             375 375 375 370                               120130 120130     120130 120130 120124   120130                                   120124     120124 120124 13084   120124 5031   115093     120124           8     8       8       8 2     6 23 23 23   23 1         5           1018           1018 1012 1012   6   1018 1018 4     1018         1018 13 13   1005     1018 13140 13140 13140 13140 69 69 69 69 69 26 26   43 43       13140     43     13140   4676 8464   8434 30         30               30 30 16   14   30 30 30   30                                                   1018   1018 8681 8681     8681   52     8681 226 226 226 181   45 45     8455       8455     8443 12         12         1018                 3 3     3 11               2982     1077 1077     1077 3125                             5     5 5 22               3337   3337 3311 3311 26         26 26   26 26                       3337 26     3337     50       50 50           624     4829 4827     4827 4026                           1  
/* globals FieldDB */
 
var FieldDBObject = require("./FieldDBObject").FieldDBObject;
var Q = require("q");
 
/**
 * @class An array backed collection that can look up elements loosely based on id or label.
 *
 * @param {Object} options Optional json initialization object
 * @property {String} primaryKey This is the optional attribute to look in the objects when doing a get or find
 * @property {Boolean} inverted This is the optional parameter for whether the collection should be inserted from the bottom or the top of the collection
 
 * @extends Object
 * @tutorial tests/CollectionTest.js
 */
var Collection = function Collection(json) {
  if (!this._fieldDBtype) {
    this._fieldDBtype = "Collection";
  }
  this.debug("Constructing a collection");
  if (!json) {
    json = {};
  }
  /* accepts just an array in construction */
  if (Object.prototype.toString.call(json) === "[object Array]") {
    json = {
      collection: json
    };
  }
 
  // if (json && json.corpus) {
  //   this.corpus = json.corpus;
  // }
 
  for (var member in json) {
    if (!json.hasOwnProperty(member) || member === "collection" /* set collection after all else has been set */ ) {
      continue;
    }
    this[member] = json[member];
  }
  Iif (!this.primaryKey) {
    var defaultKey = "id"; /*TODO try finding the key that exists in all objects if id doesnt exist? */
    this.debug("  Using default primary key of " + defaultKey);
    this.primaryKey = defaultKey;
  }
  if (json.collection) {
    this.collection = json.collection;
  }
  this.debug("  array of length " + this.collection.length);
  Object.apply(this, arguments);
};
 
Collection.notWorthSortingSize = 100;
/** @lends Collection.prototype */
Collection.prototype = Object.create(Object.prototype, {
  constructor: {
    value: Collection
  },
 
  fieldDBtype: {
    get: function() {
      return this._fieldDBtype;
    },
    set: function(value) {
      if (value !== this.fieldDBtype) {
        this.warn("Using type " + this.fieldDBtype + " when the incoming object was " + value);
      }
    }
  },
 
  /**
   * Can be set to true to debug all collections, or false to debug no collections and true only on the instances of objects which
   * you want to debug.
   *
   * @type {Boolean}
   */
  debugMode: {
    get: function() {
      Eif (this.perObjectDebugMode === undefined) {
        return false;
      } else {
        return this.perObjectDebugMode;
      }
    },
    set: function(value) {
      if (value === this.perObjectDebugMode) {
        return;
      }
      if (value === null || value === undefined) {
        delete this.perObjectDebugMode;
        return;
      }
      this.perObjectDebugMode = value;
    }
  },
  debug: {
    value: function() {
      return FieldDBObject.prototype.debug.apply(this, arguments);
    }
  },
  verboseMode: {
    get: function() {
      if (this.perObjectVerboseMode === undefined) {
        return false;
      } else {
        return this.perObjectVerboseMode;
      }
    },
    set: function(value) {
      if (value === this.perObjectVerboseMode) {
        return;
      }
      if (value === null || value === undefined) {
        delete this.perObjectVerboseMode;
        return;
      }
      this.perObjectVerboseMode = value;
    }
  },
  verbose: {
    value: function() {
      return FieldDBObject.prototype.verbose.apply(this, arguments);
    }
  },
 
  bug: {
    value: function() {
      return FieldDBObject.prototype.bug.apply(this, arguments);
    }
  },
  confirm: {
    value: function() {
      return FieldDBObject.prototype.confirm.apply(this, arguments);
    }
  },
  warn: {
    value: function() {
      return FieldDBObject.prototype.warn.apply(this, arguments);
    }
  },
  todo: {
    value: function() {
      return FieldDBObject.prototype.todo.apply(this, arguments);
    }
  },
  render: {
    value: function() {
      return FieldDBObject.prototype.render.apply(this, arguments);
    }
  },
  ensureSetViaAppropriateType: {
    value: function() {
      return FieldDBObject.prototype.ensureSetViaAppropriateType.apply(this, arguments);
    }
  },
 
  application: {
    get: function() {
      return FieldDBObject.application;
    }
  },
 
  collection: {
    get: function() {
      if (!this._collection) {
        this._collection = [];
      }
      return this._collection;
    },
    set: function(value) {
      if (value === this._collection || value === [] && this._collection === []) {
        return;
      }
      if (!value || value.length === 0) {
        this._collection = [];
        return;
      }
      Iif (Object.prototype.toString.call(value) !== "[object Array]") {
        this.bug("Cannot set collection to an object, only an array", value);
        return;
      // throw new Error("Cannot set collection to an object, only an array");
      }
      for (var itemIndex = 0; itemIndex < value.length; itemIndex++) {
        var item = value[itemIndex];
        Iif (!item) {
          this.warn("item " + itemIndex + "is  (" + item + ") undefined or empty, not adding it to the collection " + this.fieldDBtype, item);
        } else {
          this.add(item);
        }
      }
      return this._collection;
    }
  },
 
  getKeys: {
    value: function() {
      var self = this;
 
      return this.collection.map(function(item) {
        return self.getSanitizedDotNotationKey(item);
      });
    }
  },
 
  sorted: {
    get: function() {
      if (this.length && this.length < Collection.notWorthSortingSize && this._sorted) {
        return true;
      }
    },
    set: function(value) {
      this._sorted = value;
    //TODO if becoming sorted and worth sorting, do sort now
    }
  },
 
  /**
   * Loops through the collection (inefficiently, from start to end) to find
   * something which matches.
   * TODO add sorted option with faster search
   *
   * @param  {String} arg1  If run with only one argument, this is the string to look for in the primary keys.
   * @param  {String} arg2  If run with two arguments, this is the string to look for in the first argument
   * @param  {Boolean} fuzzy If run with a truthy value, will do a somewhat fuzzy search for the string anywhere in the key TODO use a real fuzzy search library if available.
   * @return {Array}       An array of found items [] if none are found TODO decide if we want to return null instead of [] when there were no results.
   */
  find: {
    value: function(arg1, arg2, fuzzy) {
      var results = [],
        searchingFor,
        optionalKeyToIdentifyItem,
        sanitzedSearchingFor;
 
      if (arg1 && arg2) {
        searchingFor = arg2;
        optionalKeyToIdentifyItem = arg1;
      } else if (arg1 && !arg2) {
        searchingFor = arg1;
      }
 
      optionalKeyToIdentifyItem = optionalKeyToIdentifyItem || this.primaryKey || "id";
      // this.debug("find is searchingFor", searchingFor);
      if (!searchingFor) {
        return results;
      }
 
      if (Object.prototype.toString.call(searchingFor) === "[object Array]") {
        this.bug("User is using find on an array... ths is best re-coded to use search or something else.", searchingFor);
        this.todo("User is using find on an array... ths is best re-coded to use search or something else. Instead running find only on the first item in the array.");
        searchingFor = searchingFor[0];
      }
 
      if (typeof searchingFor === "object" && !(searchingFor instanceof RegExp)) {
        // this.debug("find is searchingFor an object", searchingFor);
        if (Object.keys(searchingFor).length === 0) {
          return results;
        }
 
        var key = searchingFor[this.primaryKey];
        if (!key && this.INTERNAL_MODELS && this.INTERNAL_MODELS.item && typeof this.INTERNAL_MODELS.item === "function" && !(searchingFor instanceof this.INTERNAL_MODELS.item)) {
          searchingFor = new this.INTERNAL_MODELS.item(searchingFor);
        } else Iif (!key && !(searchingFor instanceof FieldDBObject)) {
          searchingFor = new FieldDBObject(searchingFor);
        } else Iif (!key) {
          this.bug("This searchingFor is a object, and has no key. this is a problem. ", searchingFor);
        }
        key = searchingFor[this.primaryKey];
        searchingFor = key;
      // this.debug("find is searchingFor an object whose key is ", searchingFor);
      }
 
      if (this[searchingFor] && typeof this[searchingFor] !== "function") {
        results.push(this[searchingFor]);
      }
      if (fuzzy) {
        sanitzedSearchingFor = new RegExp(".*" + this.sanitizeStringForPrimaryKey(searchingFor) + ".*", "i");
        searchingFor = new RegExp(".*" + searchingFor + ".*", "i");
        this.debug("fuzzy ", searchingFor, sanitzedSearchingFor);
      }
      // this.debug("searching for somethign with indexOf", searchingFor);
      if (!searchingFor || !searchingFor.test || typeof searchingFor.test !== "function") {
        /* if not a regex, the excape it */
        Eif (searchingFor && searchingFor.indexOf && searchingFor.indexOf("/") !== 0) {
          searchingFor = FieldDBObject.regExpEscape(searchingFor);
        }
        searchingFor = new RegExp("^" + searchingFor + "$");
      }
      this.debug("searchingFor", searchingFor);
      for (var index = 0; index < this.collection.length; index++) {
        if (searchingFor.test(this.collection[index][optionalKeyToIdentifyItem])) {
          // avoid having the same entry twice
          if (!results[0] || results[0] !== this.collection[index]) {
            results.push(this.collection[index]);
          }
          this.debug("Found a match ", results);
        } else Iif (fuzzy && sanitzedSearchingFor.test(this.collection[index][optionalKeyToIdentifyItem])) {
          if (!results[0] || results[0] !== this.collection[index]) {
            results.push(this.collection[index]);
          }
        }
      }
      this.debug("Found total matches ", results.length);
      // If this is fuzzy find and there are multiple matches, move the exact match first.
      if (results && results.length > 1 && fuzzy) {
        this.debug("lets look for the best result where " + optionalKeyToIdentifyItem + " = " + arg2, results.length);
        for (var i = results.length - 1; i >= 0; i--) {
          if (i !== 0 && results[i] && results[i][optionalKeyToIdentifyItem] === arg2) {
            var bestMatch = results.splice(i);
            this.debug("a pefect match  ", bestMatch);
            results.unshift(bestMatch[0]);
          }
        }
      }
      return results;
    }
  },
 
  fuzzyFind: {
    value: function(searchingFor, optionalKeyToIdentifyItem) {
 
      return this.find(searchingFor, optionalKeyToIdentifyItem, true);
    }
  },
 
  set: {
    value: function(searchingFor, value, optionalKeyToIdentifyItem, optionalInverted) {
      optionalKeyToIdentifyItem = optionalKeyToIdentifyItem || this.primaryKey || "id";
 
      if (optionalInverted === null || optionalInverted === undefined) {
        optionalInverted = this.inverted;
      }
 
      if (!searchingFor && value) {
        //previously code in the add function
 
        this.debug("  the constructor of this before casting it ");
        value = FieldDBObject.convertDocIntoItsType(value);
        this.debug(" checking the constructor of this after casting it ");
 
        if (value &&
          this.INTERNAL_MODELS &&
          this.INTERNAL_MODELS.item &&
          typeof this.INTERNAL_MODELS.item === "function" &&
          !(value instanceof this.INTERNAL_MODELS.item) &&
           value.constructor.toString() !== this.INTERNAL_MODELS.item.toString() &&
          // value.constructor.toString().substring(9, 22) !== "FieldDBObject" &&
          !(this.INTERNAL_MODELS.item.compatibleWithSimpleStrings && typeof value === "string")) {
 
          // this.debug("adding a internamodel ", value);
          // if (!this.INTERNAL_MODELS.item.fieldDBtype || this.INTERNAL_MODELS.item.fieldDBtype !== "Document") {
          this.debug("casting an item to match the internal model which this collection requires ", this.INTERNAL_MODELS.item, value.constructor.toString());
          if (typeof value.toJSON === "function") {
            this.debug(" why defereincing this?");
          // value = value.toJSON();
          }
          value = new this.INTERNAL_MODELS.item(value);
        // } else {
        //   if (value.constructor === Object) {
        //     this.warn("this is going to be a FieldDBObject, even though its supposed to be in a collection of Documents.", value);
        //     value = new FieldDBObject(value);
        //   } else {
        //     this.warn("this is " + value[this.primaryKey] + " already some sort of an object: " + value.fieldDBtype);
        //   }
        // }
        } else {
          this.debug("  item to set was already of the right type for " + this.fieldDBtype, value);
        }
        searchingFor = this.getSanitizedDotNotationKey(value);
        if (!searchingFor) {
          this.bug("The primary key `" + this.primaryKey + "` is undefined on this object, it cannot be added! ", value);
          return;
        // throw new Error("The primary key `" + this.primaryKey + "` is undefined on this object, it cannot be added! Type: " + value.fieldDBtype);
        }
        this.debug("adding " + searchingFor);
 
      }
 
      if (value && this[searchingFor] && (value === this[searchingFor] || (typeof this[searchingFor].equals === "function" && this[searchingFor].equals(value)))) {
        this.debug("Not setting " + searchingFor + ", it  was already the same in the collection");
        return this[searchingFor];
      }
 
      Iif (value === null || value === undefined) {
        this.remove(searchingFor, optionalKeyToIdentifyItem);
      }
 
      for (var index in this.collection) {
        Iif (!this.collection.hasOwnProperty(index)) {
          continue;
        }
        if (this.collection[index][optionalKeyToIdentifyItem] === searchingFor) {
          this.debug("found a match in the _collection, ", this.collection[index].equals);
          // this.collection[index].debugMode = true;
          // value.debugMode = true;
          Eif (this.collection[index] !== value ||
            (typeof this.collection[index].equals === "function" && !this.collection[index].equals(value))
          ) {
            Eif (typeof this.collection[index].merge === "function") {
              this.warn("Merging an existing _collection member " + searchingFor + " at index " + index + " (they have the same key but are not equal, nor the same object) ");
              this.collection[index].merge("self", value);
            } else {
              this.warn("Overwriting an existing _collection member " + searchingFor + " at index " + index + " (they have the same key but are not equal, nor the same object) ");
              this.warn("Overwriting ", this.collection[index], "->", value);
              this.collection[index] = value;
            }
          }
          return this.collection[index];
        }
      }
      /* if not a reserved attribute, set on object for dot notation access */
      Eif (["collection", "primaryKey", "find", "set", "add", "inverted", "toJSON", "length", "encrypted", "confidential", "decryptedMode"].indexOf(searchingFor) === -1) {
        this[searchingFor] = value;
        /* also provide a case insensitive cleaned version if the key can be lower cased */
        if (searchingFor && typeof searchingFor.toLowerCase === "function") {
          this[searchingFor.toLowerCase().replace(/_/g, "")] = value;
        }
 
      } else {
        this.warn("An item was added to the collection which has a reserved word for its key... dot notation will not work to retreive this object, but find() will work. ", value);
      }
 
      Eif (value && typeof value === "object") {
        value.parent = this;
      }
 
      if (optionalInverted) {
        this.collection.unshift(value);
      } else {
        this.collection.push(value);
      }
      return this[searchingFor];
    // return value;
    }
  },
 
  length: {
    get: function() {
      Eif (this.collection) {
        return this.collection.length;
      } else {
        return 0;
      }
    }
  },
 
  primaryKey: {
    get: function() {
      this.debug(this.id + "  getting collection prmary key " + this._primaryKey);
      return this._primaryKey || "id";
    },
    set: function(value) {
      this.debug(this.id + "setting collection prmary key " + this._primaryKey);
      Eif (value) {
        this._primaryKey = value;
      }
    }
  },
 
  /**
   * This function should be used when trying to access a member using its id
   *
   * Originally we used this for import to create datum field labels: .replace(/[-""+=?./\[\]{}() ]/g,"")
   *
   * @param  {Object} member An object of the type of objects in this collection
   * @return {String}        The value of the primary key which is save to use as dot notation
   */
  getSanitizedDotNotationKey: {
    value: function(member) {
      Iif (!this.primaryKey) {
        this.bug("The primary key of this collection " + this.id + " is undefined, nothing can be added!", this);
        return;
      // throw new Error("The primary key of this collection " + this.id + " is undefined, nothing can be added!").stack;
      }
      var value = member[this.primaryKey];
      if (!value) {
        this.warn("This object is missing a value for the primary key " + this.primaryKey + "...not adding it because it will be hard to find in the collection.");
        this.debug("  not adding: ", member);
        return;
      }
      if (typeof value.trim === "function") {
        value = value.trim();
      }
      var oldValue = value;
      value = this.sanitizeStringForPrimaryKey(value);
      if (value !== oldValue && this.fieldDBtype !== "DatumStates") {
        this.debug("The sanitized the dot notation key of this object is not the same as its primaryKey: " + oldValue + " -> " + value);
      }
      return value;
    }
  },
 
  /**
   * Adds to the bottom of the collection
   *
   * @param  {Object} value a simple object, and/or  an array of objects or items of the type of this collection.
   * @return {Array}       returns a reference to the added item(s)
   */
  add: {
    value: function(value) {
      if (value && Object.prototype.toString.call(value) === "[object Array]") {
        for (var itemIndex = 0; itemIndex < value.length; itemIndex++) {
          value[itemIndex] = this.add(value[itemIndex]);
        }
        return value;
      }
 
      return this.set(null, value);
    }
  },
 
  concat: {
    value: function(anotherCollection) {
      if (anotherCollection && anotherCollection._collection) {
        return this.add(anotherCollection._collection);
      }
      if (!anotherCollection) {
        return this;
      }
      this.add(anotherCollection);
      return this;
    }
  },
 
  push: {
    value: function(value) {
      // self.debug(this.collectioan);
      return this.set(null, value, null, false);
    }
  },
 
  unshift: {
    value: function(value) {
      return this.set(null, value, null, true);
    }
  },
 
  pop: {
    value: function() {
      Iif (!this._collection || this._collection.length < 1) {
        return;
      }
      var removed = this._collection.pop();
      Iif (!removed) {
        return;
      }
      var key = this.getSanitizedDotNotationKey(removed);
      Iif (!key) {
        this.warn("This item had no primary key, it will only be removed from the collection. ", removed);
      }
 
      Eif (this[key]) {
        this.debug("removed dot notation for ", key);
        delete this[key];
      }
      key = key + "";
      Eif (this[key.toLowerCase().replace(/_/g, "")]) {
        this.debug("removed dot notation for ", key.toLowerCase().replace(/_/g, ""));
        delete this[key.toLowerCase().replace(/_/g, "")];
      }
      return removed;
    }
  },
 
  shift: {
    value: function() {
      Iif (!this._collection || this._collection.length < 1) {
        return;
      }
      var removed = this._collection.shift();
      Iif (!removed) {
        return;
      }
      var key = this.getSanitizedDotNotationKey(removed);
      Iif (!key) {
        this.warn("This item had no primary key, it will only be removed from the collection. ", removed);
      }
 
      Eif (this[key]) {
        this.debug("removed dot notation for ", key);
        delete this[key];
      }
      key = key + "";
      Eif (this[key.toLowerCase().replace(/_/g, "")]) {
        this.debug("removed dot notation for ", key.toLowerCase().replace(/_/g, ""));
        delete this[key.toLowerCase().replace(/_/g, "")];
      }
      return removed;
    }
  },
 
  remove: {
    value: function(requestedRemoveFor, optionalKeyToIdentifyItem) {
      Iif (optionalKeyToIdentifyItem) {
        this.todo("remove optionalKeyToIdentifyItem " + optionalKeyToIdentifyItem);
      }
      var removed = [],
        itemIndex,
        key,
        searchingFor = [],
        self = this;
 
      if (Object.prototype.toString.call(requestedRemoveFor) !== "[object Array]") {
        requestedRemoveFor = [requestedRemoveFor];
      }
      // Look for the real item(s) in the collection
      requestedRemoveFor.map(function(requestedRemoveItem) {
        searchingFor = searchingFor.concat(self.find(requestedRemoveItem));
      });
 
      this.debug("requested remove of ", searchingFor);
      if (searchingFor.length === 0) {
        this.warn("Didn't need to remove object(s) which were not in the collection.");
        return removed;
      }
      /*
       * For every item, delete the dot reference to it
       */
      for (itemIndex = 0; itemIndex < searchingFor.length; itemIndex++) {
        Iif (!searchingFor[itemIndex] || searchingFor[itemIndex] === {}) {
          this.debug("skipping ", searchingFor[itemIndex]);
          continue;
        }
        key = this.getSanitizedDotNotationKey(searchingFor[itemIndex]);
        Iif (!key) {
          this.warn("This item had no primary key, it will only be removed from the collection. ", searchingFor[itemIndex]);
        }
 
        if (this[key]) {
          this.debug("removed dot notation for ", key);
          delete this[key];
        }
        key = key + "";
        if (this[key.toLowerCase().replace(/_/g, "")]) {
          this.debug("removed dot notation for ", key.toLowerCase().replace(/_/g, ""));
          delete this[key.toLowerCase().replace(/_/g, "")];
        }
 
      }
 
      /*
       * For every item in the collection, if it matches, remove it from the collection
       */
      for (itemIndex = this.collection.length - 1; itemIndex >= 0; itemIndex--) {
        if (searchingFor.indexOf(this.collection[itemIndex]) > -1 && removed.indexOf(this.collection[itemIndex]) === -1) {
          var thisremoved = this.collection.splice(itemIndex, 1);
          removed = removed.concat(thisremoved);
          // Find out if each removed item was requested
          for (var removedIndex = 0; removedIndex < thisremoved.length; removedIndex++) {
            if (typeof requestedRemoveFor[0] === "object" && typeof thisremoved[removedIndex].equals === "function") {
              var itMatches = false;
              for (var requestedIndex = 0; requestedIndex < requestedRemoveFor.length; requestedIndex++) {
                if (thisremoved[removedIndex].equals(requestedRemoveFor[requestedIndex])) {
                  itMatches = true;
                }
              }
              if (!itMatches) {
                this.warn("One of the requested removal items doesnt match exactly what was removed ");
                this.debug("One of the requested removal items doesnt match exactly ", requestedRemoveFor, "-> ", thisremoved[removedIndex]);
              }
            }
          }
        }
      }
 
      Iif (removed.length === 0) {
        this.warn("Didn't remove object(s) which were not in the collection.", searchingFor);
      }
      this.removedCollection = this.removedCollection || [];
      this.removedCollection = this.removedCollection.concat(removed);
      return removed;
    }
  },
 
  indexOf: {
    value: function(doc) {
      Iif (!this._collection || this.collection.length === 0) {
        return -1;
      }
      for (var docIndex = 0; docIndex < this._collection.length; docIndex++) {
        var key = doc[this.primaryKey];
        if (!key) {
          doc = this.find(doc);
          if (doc && doc.length > 0) {
            doc = doc[0];
          } else {
            return -1;
          }
          key = doc[this.primaryKey];
        }
        if (this._collection[docIndex][this.primaryKey] === key) {
          return docIndex;
        }
 
      }
      return -1;
    }
  },
 
  get: {
    value: function(index) {
      Iif (index === undefined || index === null || !this._collection) {
        return;
      }
      return this._collection[index];
    }
  },
 
  reorder: {
    value: function(old_index, new_index) {
      if (typeof old_index === "object") {
        old_index = this.indexOf(old_index);
      }
      Iif (new_index >= this._collection.length) {
        var k = new_index - this._collection.length;
        while ((k--) + 1) {
          this._collection.push(undefined);
        }
      }
      this._collection.splice(new_index, 0, this._collection.splice(old_index, 1)[0]);
    }
  },
 
  unsaved: {
    get: function() {
      for (var itemIndex = this._collection.length - 1; itemIndex >= 0; itemIndex--) {
        if (this._collection[itemIndex].unsaved) {
          this._unsaved = true;
          return this._unsaved;
        }
      }
      this._unsaved = false;
      return this._unsaved;
    },
    set: function(value) {
      this._unsaved = !!value;
    }
  },
 
  // calculateUnsaved: {
  //   value: function() {
  //     var previous = new this.constructor(this.fossil);
  //     var current = new this.constructor(this);
 
  //     if (previous.equals(current)) {
  //       this.warn("The " + this.fieldDBtype + "collection didnt actually change. Not marking as editied");
  //       this._unsaved = false;
  //     } else {
  //       this._unsaved = true;
  //     }
  //     return this._unsaved;
  //   }
  // },
 
  save: {
    value: function(optionalUserWhoSaved, saveEvenIfSeemsUnchanged, optionalUrl) {
      var deferred = Q.defer(),
        self = this,
        promises = [];
 
      this.saving = true;
      this.whenReady = deferred.promise;
 
      this.map(function(item) {
        self.debug("saving ", item);
        Eif (item) {
          promises.push(item.save(optionalUserWhoSaved, saveEvenIfSeemsUnchanged, optionalUrl));
        } else {
          console.log("not saving this item", item);
        }
      });
 
      this.warn("Saving " + promises.length + " items out of a collection with  " + this.length + " items.");
 
      Q.allSettled(promises).done(function(results) {
        self.warn("Saved a collection", results.length);
        // self.debug(results);
        self.saving = false;
        deferred.resolve(self);
        return self;
      });
 
      // .then(function(results) {
      //   self.warn("Saved a collection", results.length);
      //   // self.debug(results);
      //   self.saving = false;
      //   deferred.resolve(self);
      //   return self;
      // }, function(results) {
      //   self.warn("Saved a collection,", results.length);
      //   // self.debug(results);
      //   self.saving = false;
      //   deferred.resolve(self);
      //   return self;
      // }).fail(function(error) {
      //   console.error(error.stack, self);
      //   deferred.reject(error);
      // });
 
      return deferred.promise;
    }
  },
 
  toJSON: {
    value: function(includeEvenEmptyAttributes, removeEmptyAttributes) {
      var self = this;
 
      var json = this._collection.map(function(item) {
        Eif (typeof item.toJSON === "function") {
          self.debug("This item has a toJSON, which we will call instead");
          return item.toJSON(includeEvenEmptyAttributes, removeEmptyAttributes);
        } else {
          return item;
        }
      });
 
      return json;
    }
  },
 
  /**
   * Creates a deep copy of the object (not a reference)
   * @return {Object} a near-clone of the objcet
   */
  clone: {
    value: function(includeEvenEmptyAttributes) {
      var self = this;
      var collection = this._collection.map(function(item) {
        Eif (typeof item.clone === "function") {
          self.debug("This item has a clone, which we will call instead");
          return item.clone(includeEvenEmptyAttributes);
        } else {
          return JSON.parse(JSON.stringify(item));
        }
      });
 
      var json = {
        primaryKey: this.primaryKey,
        collection: collection,
        capitalizeFirstCharacterOfPrimaryKeys: this.capitalizeFirstCharacterOfPrimaryKeys
      };
 
      var newInstance = new this.constructor(json);
      newInstance.corpus = this.corpus;
      return newInstance;
    }
  },
 
  filter: {
    get: function() {
      Eif (this._collection && typeof this._collection.filter === "function") {
        var self = this;
        return function(callback) {
          return this._collection.filter.apply(self._collection, [callback]);
        };
      } else {
        return undefined;
      }
    }
  },
 
  forEach: {
    get: function() {
      if (this._collection && typeof this._collection.forEach === "function") {
        var self = this;
        return function(callback) {
          return this._collection.forEach.apply(self._collection, [callback]);
        };
      } else {
        return undefined;
      }
    }
  },
 
  map: {
    get: function() {
      Eif (this._collection && typeof this._collection.map === "function") {
        var self = this;
        return function(callback) {
          return this._collection.map.apply(self._collection, [callback]);
        };
      } else {
        return undefined;
      }
    }
  },
 
  /**
   *  Cleans a value to be safe for a file system or the key of a hash
   *
   * @param  String value the potential primary key to be cleaned
   * @return String       the value cleaned and safe as a primary key
   */
  sanitizeStringForPrimaryKey: {
    value: function(value) {
      this.debug("sanitizeStringForPrimaryKey " + value);
      Iif (!value) {
        return null;
      }
      value = FieldDBObject.prototype.sanitizeStringForFileSystem.apply(this, arguments);
      if (value && value.trim) {
        value = this.camelCased(value);
      }
      return value;
    }
  },
  capitalizeFirstCharacterOfPrimaryKeys: {
    value: {
      get: function() {
        if (this._capitalizeFirstCharacterOfPrimaryKeys === undefined) {
          return false;
        }
        return this._capitalizeFirstCharacterOfPrimaryKeys;
      },
      set: function(value) {
        this._capitalizeFirstCharacterOfPrimaryKeys = value;
      }
    }
  },
  camelCased: {
    value: function(value) {
      Iif (!value) {
        return null;
      }
      Eif (value.replace) {
        value = value.replace(/_([a-zA-Z])/g, function(word) {
          return word[1].toUpperCase();
        });
        if (this.capitalizeFirstCharacterOfPrimaryKeys) {
          value = value[0].toUpperCase() + value.substring(1, value.length);
        } else {
          value = value[0].toLowerCase() + value.substring(1, value.length);
        }
      }
      return value;
    }
  },
 
  equals: {
    value: function(anotherCollection) {
      Iif (!anotherCollection) {
        return false;
      }
      Iif (!this._collection && !anotherCollection._collection) {
        return true;
      }
 
      Iif (!this._collection || !anotherCollection._collection) {
        return false;
      }
 
      if (this._collection.length !== anotherCollection._collection.length) {
        return false;
      }
      // this.debugMode = true;
      for (var itemIndex = this._collection.length - 1; itemIndex >= 0; itemIndex--) {
        var itemInThisCollection = this._collection[itemIndex];
        var itemInAnotherCollection = anotherCollection.find(itemInThisCollection[anotherCollection.primaryKey])[0];
        this.debug("Are these equal ", itemInThisCollection, itemInAnotherCollection);
        // itemInThisCollection.debugMode = true;
        if (!itemInThisCollection.equals(itemInAnotherCollection)) {
          return false;
        }
      }
      // this.debugMode = false;
 
      return true;
    }
  },
 
  merge: {
    value: function(callOnSelf, anotherCollection, optionalOverwriteOrAsk) {
      var aCollection,
        resultCollection,
        overwrite,
        localCallOnSelf,
        self = this;
 
      if (callOnSelf === "self") {
        this.debug("Merging into myself. ");
        aCollection = this;
      } else {
        aCollection = callOnSelf;
      }
      resultCollection = this;
      if (!optionalOverwriteOrAsk) {
        optionalOverwriteOrAsk = "";
      }
 
      Iif (!anotherCollection || anotherCollection.length === 0) {
        this.debug("The new collection was empty, not merging.", anotherCollection);
        return resultCollection;
      }
 
      if (!(anotherCollection instanceof aCollection.constructor) || anotherCollection.constructor.toString() !== aCollection.constructor.toString()) {
        this.debug("The anotherCollection  isnt of the same type as aCollection ", aCollection.constructor, anotherCollection.constructor);
        anotherCollection = new aCollection.constructor(anotherCollection);
      } else {
        this.debug("The anotherCollection  is  the same type as aCollection ", aCollection.constructor, anotherCollection.constructor);
      }
 
      aCollection._collection.map(function(anItem) {
        var idToMatch = anItem[aCollection.primaryKey].toLowerCase();
        var anotherItem = anotherCollection[idToMatch];
        var resultItem = resultCollection[idToMatch];
        if (!resultItem && typeof anItem.constructor === "function") {
          self.debug("Cloning into anItem into a fielddbObjects ifits not one already");
          var json = anItem.toJSON ? anItem.toJSON() : anItem;
          resultItem = FieldDBObject.convertDocIntoItsType(json);
          var existingInCollection = resultCollection.find(resultItem);
          if (existingInCollection.length === 0) {
            self.debug("This item wasnt in the result collection yet, adding it.", resultItem);
            resultItem = resultCollection.add(resultItem);
          } else {
            resultItem = existingInCollection[0];
            self.debug("resultItem was already in the resultCollection  ", existingInCollection, resultItem);
          }
        }
 
        if (anItem !== aCollection[idToMatch]) {
          // TODO why was this bug, then warn, and now showing for every context?
          // self.warn(" Looking at an anItem that should have matched the aCollection's member of " + idToMatch);
          self.debug(" Looking at an an Item that doesnt match the aCollection's member of " + idToMatch, anItem, aCollection[idToMatch]);
        }
 
        if (anotherItem === undefined) {
          // no op, the new one isn't set
          self.debug(idToMatch + " was missing in new collection");
        } else if (resultItem === anotherItem || (typeof resultItem.equals === "function" && resultItem.equals(anotherItem))) {
          // no op, they are equal enough
          self.debug(idToMatch + " were equal.", anItem, anotherItem);
        } else Iif (!anItem || anItem === [] || anItem.length === 0 || anItem === {}) {
          self.debug(idToMatch + " was previously empty, taking the new value");
          resultCollection[idToMatch] = anotherItem;
        } else {
          //  if two arrays: concat
          Iif (Object.prototype.toString.call(anItem) === "[object Array]" && Object.prototype.toString.call(anotherItem) === "[object Array]") {
            self.debug(idToMatch + " was an array, concatinating with the new value", anItem, " ->", anotherItem);
            resultItem = anItem.concat(anotherItem);
 
            //TODO unique it?
            self.debug("  ", resultItem);
          } else {
            // if two fielddbObjects: recursively merge
            Eif (typeof resultItem.merge === "function") {
              if (callOnSelf === "self") {
                localCallOnSelf = callOnSelf;
              } else {
                localCallOnSelf = anItem;
              }
              self.debug("Requesting merge of internal property " + idToMatch + " using method: " + localCallOnSelf);
              var result = resultItem.merge(localCallOnSelf, anotherItem, optionalOverwriteOrAsk);
              self.debug("after internal merge ", result);
              // resultCollection[idToMatch] = resultItem;
              self.debug("after internal merge ", resultItem);
 
            } else {
              overwrite = optionalOverwriteOrAsk;
              if (optionalOverwriteOrAsk.indexOf("overwrite") === -1) {
                // overwrite = self.confirm("Do you want to overwrite " + idToMatch);
                self.confirm(this.id + " I found a conflict for " + idToMatch + ", Do you want to overwrite it from " + JSON.stringify(anItem) + " -> " + JSON.stringify(anotherItem))
                  .then(function() {
                    self.debug("Overwriting contents of " + idToMatch + " (this may cause disconnection in listeners)");
                    self.debug("Overwriting  ", anItem, " ->", anotherItem);
                    resultCollection[idToMatch] = anotherItem;
                  }, function() {
                    self.debug("Not Overwriting  ", anItem, " ->", anotherItem);
                    resultCollection[idToMatch] = anItem;
                  }).fail(function(error) {
                  console.error(error.stack, self);
                });
              } else {
                self.debug("Overwriting contents of " + idToMatch + " (this may cause disconnection in listeners)");
                self.debug("Overwriting  ", anItem, " ->", anotherItem);
                resultCollection[idToMatch] = anotherItem;
              }
            }
          }
        }
      });
      Eif (anotherCollection._collection && typeof anotherCollection._collection.map === "function") {
 
        anotherCollection._collection.map(function(anotherItem) {
          var idToMatch = anotherItem[aCollection.primaryKey];
          var anItem = aCollection[idToMatch];
          // var resultItem = resultCollection[idToMatch];
 
          if (anotherItem !== anotherCollection[idToMatch]) {
            // self.debug(" Looking at an anItem that doesnt match the anotherCollection's member of " + idToMatch);
            self.debug(" Looking at an anItem that doesnt match the anotherCollection's member of " + idToMatch, anotherItem, anotherCollection[idToMatch]);
          }
 
          if (anItem === undefined) {
            self.debug(idToMatch + " was missing in target, adding it");
            var existingInCollection = resultCollection.find(anotherItem);
            if (existingInCollection.length === 0) {
              resultCollection.add(anotherItem);
            } else {
              anotherItem = existingInCollection[0];
              self.debug("anotherItem was already in the resultCollection ", existingInCollection, anotherItem);
            }
 
          } else Iif (anotherItem === undefined) {
            // no op, the new one isn't set
            self.debug(idToMatch + " was oddly undefined");
            resultCollection[idToMatch] = anItem;
          } else if (anItem === anotherItem || (typeof anItem.equals === "function" && anItem.equals(anotherItem))) {
            // no op, they are equal enough
            // self.debug(idToMatch + " were equal.", anItem, anotherItem);
            resultCollection[idToMatch] = anItem;
          } else Iif (!anotherItem || anotherItem === [] || anotherItem.length === 0 || anotherItem === {}) {
            self.warn(idToMatch + " was empty in the new collection, so it was replaced with an empty anItem.");
            resultCollection[idToMatch] = anotherItem;
          } else {
            // both exist and are not equal, and so have already been merged above.
            self.debug(idToMatch + " existed in both and are not equal, and so have already been merged above.");
          }
        });
      }
 
      return resultCollection;
    }
  },
 
  encrypted: {
    get: function() {
      return;
    },
    set: function(value) {
      Eif (this._collection) {
        Iif (this._collection.map === undefined) {
          this.warn("This collection isn't an array, this is odd", this);
        }
        this._collection.map(function(item) {
          item.encrypted = value;
        });
      }
    }
  },
 
  confidential: {
    get: function() {
      return;
    },
    set: function(value) {
      Eif (this._collection) {
        Iif (this._collection.map === undefined) {
          this.warn("This collection isn't an array, this is odd", this);
        }
        this._collection.map(function(item) {
          item.confidential = value;
        });
      }
    }
  },
 
  decryptedMode: {
    get: function() {
      if (this.application) {
        return this.application.decryptedMode;
      }
      // if not running in an app, dont need to demonstrate a mask the data if its decryptable
      return this._decryptedMode;
    },
    set: function(value) {
      Iif (this.application) {
        this.application.decryptedMode = value;
      } else {
        this._decryptedMode = value;
        this._collection.map(function(item) {
          item.decryptedMode = value;
        });
      }
    }
  },
 
  corpus: {
    get: function() {
      var db = null;
      // this.debugMode = true;
      if (this._corpus) {
        db = this._corpus;
        this.debug("this " + this._id + " has a _corpus hard coded inside it, using it.", db);
      } else Iif (FieldDBObject.application && FieldDBObject.application._corpus) {
        db = FieldDBObject.application._corpus;
        this.debug("this " + this._id + " is running in the context where FieldDBObject.application._corpus is defined, using it.", db);
      } else {
 
        try {
          Eif (FieldDB && FieldDB["Database"]) {
            // db = FieldDB["Database"].prototype;
            this.debug("  using the Database.prototype to run db calls for " + this._id + ", this could be problematic " + this._id + " .");
            this.debug(" the database", db);
          }
        } catch (e) {
          var message = e ? e.message : " unknown error in getting the corpus";
          if (message !== "FieldDB is not defined") {
            this.warn(this._id + "Cant get the corpus, cant find the Database class.", e);
            if (e) {
              this.warn("  stack trace" + e.stack);
            }
          }
        }
      }
      if (!db) {
        this.warn("Operations that need a corpus/database wont work for the " + this._id + " object");
      }
 
      return db;
    },
    set: function(value) {
      Iif (value && value.dbname && this.dbname && value.dbname !== this.dbname) {
        this.warn("The corpus " + value.db + " cant be set on this item, its db is different" + this.dbname);
        return;
      }
      this.debug("setting corpus ", value);
      this._corpus = value;
    }
  },
 
  dbname: {
    get: function() {
      return;
    },
    set: function(value) {
      if (this._collection) {
        Iif (this._collection.map === undefined) {
          this.warn("This collection isn't an array, this is odd", this);
        }
        this._collection.map(function(item) {
          item.dbname = value;
        });
      }
    }
  },
 
  INTERNAL_MODELS: {
    value: {
      item: FieldDBObject
    }
  }
 
});
 
exports.Collection = Collection;