/**
 * node-compress-commons
 *
 * Copyright (c) 2014 Chris Talkington, contributors.
 * Licensed under the MIT license.
 * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT
 */
var zipUtil = require('./util');

var DATA_DESCRIPTOR_FLAG = 1 << 3;
var ENCRYPTION_FLAG = 1 << 0;
var NUMBER_OF_SHANNON_FANO_TREES_FLAG = 1 << 2;
var SLIDING_DICTIONARY_SIZE_FLAG = 1 << 1;
var STRONG_ENCRYPTION_FLAG = 1 << 6;
var UFT8_NAMES_FLAG = 1 << 11;

var GeneralPurposeBit = module.exports = function() {
  if (!(this instanceof GeneralPurposeBit)) {
    return new GeneralPurposeBit();
  }

  this.descriptor = false;
  this.encryption = false;
  this.utf8 = false;
  this.numberOfShannonFanoTrees = 0;
  this.strongEncryption = false;
  this.slidingDictionarySize = 0;

  return this;
};

GeneralPurposeBit.prototype.encode = function() {
  return zipUtil.getShortBytes(
    (this.descriptor ? DATA_DESCRIPTOR_FLAG : 0) |
    (this.utf8 ? UFT8_NAMES_FLAG : 0) |
    (this.encryption ? ENCRYPTION_FLAG : 0) |
    (this.strongEncryption ? STRONG_ENCRYPTION_FLAG : 0)
  );
};

GeneralPurposeBit.prototype.parse = function(buf, offset) {
  var flag = zipUtil.getShortBytesValue(buf, offset);
  var gbp = new GeneralPurposeBit();

  gbp.useDataDescriptor((flag & DATA_DESCRIPTOR_FLAG) !== 0);
  gbp.useUTF8ForNames((flag & UFT8_NAMES_FLAG) !== 0);
  gbp.useStrongEncryption((flag & STRONG_ENCRYPTION_FLAG) !== 0);
  gbp.useEncryption((flag & ENCRYPTION_FLAG) !== 0);
  gbp.setSlidingDictionarySize((flag & SLIDING_DICTIONARY_SIZE_FLAG) !== 0 ? 8192 : 4096);
  gbp.setNumberOfShannonFanoTrees((flag & NUMBER_OF_SHANNON_FANO_TREES_FLAG) !== 0 ? 3 : 2);

  return gbp;
};

GeneralPurposeBit.prototype.setNumberOfShannonFanoTrees = function(n) {
  this.numberOfShannonFanoTrees = n;
};

GeneralPurposeBit.prototype.getNumberOfShannonFanoTrees = function() {
  return this.numberOfShannonFanoTrees;
};

GeneralPurposeBit.prototype.setSlidingDictionarySize = function(n) {
  this.slidingDictionarySize = n;
};

GeneralPurposeBit.prototype.getSlidingDictionarySize = function() {
  return this.slidingDictionarySize;
};

GeneralPurposeBit.prototype.useDataDescriptor = function(b) {
  this.descriptor = b;
};

GeneralPurposeBit.prototype.usesDataDescriptor = function() {
  return this.descriptor;
};

GeneralPurposeBit.prototype.useEncryption = function(b) {
  this.encryption = b;
};

GeneralPurposeBit.prototype.usesEncryption = function() {
  return this.encryption;
};

GeneralPurposeBit.prototype.useStrongEncryption = function(b) {
  this.strongEncryption = b;
};

GeneralPurposeBit.prototype.usesStrongEncryption = function() {
  return this.strongEncryption;
};

GeneralPurposeBit.prototype.useUTF8ForNames = function(b) {
  this.utf8 = b;
};

GeneralPurposeBit.prototype.usesUTF8ForNames = function() {
  return this.utf8;
};