// Generated by CoffeeScript 1.9.1
(function() {
  var Commit, Head, Ref, fs,
    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    hasProp = {}.hasOwnProperty;

  fs = require('fs');

  Commit = require('./commit');

  exports.Ref = Ref = (function() {
    function Ref(name1, commit1) {
      this.name = name1;
      this.commit = commit1;
      this.repo = this.commit.repo;
    }

    Ref.prototype.toString = function() {
      return "#<Ref '" + this.name + "'>";
    };

    Ref.find_all = function(repo, type, RefClass, callback) {
      return repo.git.refs(type, {}, function(err, text) {
        var id, ids, j, len, name, names, ref, ref1, ref2;
        if (err) {
          return callback(err);
        }
        names = [];
        ids = [];
        ref1 = text.split("\n");
        for (j = 0, len = ref1.length; j < len; j++) {
          ref = ref1[j];
          if (!ref) {
            continue;
          }
          ref2 = ref.split(' '), name = ref2[0], id = ref2[1];
          names.push(name);
          ids.push(id);
        }
        return Commit.find_commits(repo, ids, function(err, commits) {
          var i, k, len1, refs;
          if (err) {
            return callback(err);
          }
          refs = [];
          for (i = k = 0, len1 = names.length; k < len1; i = ++k) {
            name = names[i];
            refs.push(new RefClass(name, commits[i]));
          }
          return callback(null, refs);
        });
      });
    };

    return Ref;

  })();

  exports.Head = Head = (function(superClass) {
    extend(Head, superClass);

    function Head() {
      return Head.__super__.constructor.apply(this, arguments);
    }

    Head.find_all = function(repo, callback) {
      return Ref.find_all(repo, "head", Head, callback);
    };

    Head.current = function(repo, callback) {
      return fs.readFile(repo.dot_git + "/HEAD", function(err, data) {
        var branch, m, ref;
        if (err) {
          return callback(err);
        }
        ref = /ref: refs\/heads\/([^\s]+)/.exec(data);
        if (!ref) {
          return callback(new Error("Current branch is not a valid branch."));
        }
        m = ref[0], branch = ref[1];
        return fs.readFile(repo.dot_git + "/refs/heads/" + branch, function(err, id) {
          return Commit.find(repo, id, function(err, commit) {
            if (err) {
              return callback(err);
            }
            return callback(null, new Head(branch, commit));
          });
        });
      });
    };

    return Head;

  })(Ref);

}).call(this);
