// Generated by IcedCoffeeScript 1.8.0-e
(function() {
  var BaseScraper, PREFIX, RedditScraper, SUBREDDIT, constants, iced, proof_text_check_to_med_id, sncmp, v_codes, __iced_k, __iced_k_noop, _ref,
    __hasProp = {}.hasOwnProperty,
    __extends = 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; };

  iced = require('iced-runtime');
  __iced_k = __iced_k_noop = function() {};

  _ref = require('./base'), sncmp = _ref.sncmp, BaseScraper = _ref.BaseScraper;

  constants = require('../constants').constants;

  v_codes = constants.v_codes;

  proof_text_check_to_med_id = require('../base').proof_text_check_to_med_id;

  PREFIX = "https://www.reddit.com";

  SUBREDDIT = PREFIX + "/r/keybaseproofs";

  exports.RedditScraper = RedditScraper = (function(_super) {
    __extends(RedditScraper, _super);

    function RedditScraper(opts) {
      RedditScraper.__super__.constructor.call(this, opts);
    }

    RedditScraper.prototype._check_args = function(args) {
      if (!(args.username != null)) {
        return new Error("Bad args to Reddit proof: no username given");
      } else if (!(args.name != null) || (args.name !== 'reddit')) {
        return new Error("Bad args to Reddit proof: type is " + args.name);
      } else {
        return null;
      }
    };

    RedditScraper.prototype._check_api_url = function(_arg) {
      var api_url, rxx, username;
      api_url = _arg.api_url, username = _arg.username;
      rxx = new RegExp("^" + SUBREDDIT, "i");
      return (api_url != null) && api_url.match(rxx);
    };

    RedditScraper.prototype.hunt2 = function(_arg, cb) {
      var err, json, name, post, posts, proof_post, proof_text_check, rc, username, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      username = _arg.username, proof_text_check = _arg.proof_text_check, name = _arg.name;
      if ((err = this._check_args({
        username: username,
        name: name
      })) != null) {
        return cb(err, {
          rc: v_codes.BAD_ARGS
        });
      }
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/Users/max/src/keybase/proofs/src/scrapers/reddit.iced",
            funcname: "RedditScraper.hunt2"
          });
          _this._get_url_body({
            url: "" + PREFIX + "/user/" + (encodeURIComponent(username)) + "/submitted.json",
            json: true,
            qs: {
              count: 25,
              cachebust: Math.random()
            }
          }, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                rc = arguments[1];
                return json = arguments[2];
              };
            })(),
            lineno: 47
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          var _i, _len;
          if ((err != null) || rc !== v_codes.OK) {
            return cb(err, {
              rc: rc
            });
          }
          if ((posts = _this.unpack_posts(json)) == null) {
            return cb(new Error("Couldn't get Reddit user " + username + "'s posts: " + json.error), {
              rc: v_codes.FAILED_PARSE
            });
          }
          proof_post = null;
          _this.log("+ Reddit user " + username + "'s posts:");
          for (_i = 0, _len = posts.length; _i < _len; _i++) {
            post = posts[_i];
            _this.log("| title: " + post.title);
            if ((_this.check_post({
              post: post,
              username: username,
              proof_text_check: proof_text_check
            })) === v_codes.OK) {
              _this.log("| Found a good post!");
              proof_post = post;
              break;
            }
          }
          _this.log("-");
          if (proof_post == null) {
            return cb(null, {
              rc: v_codes.NOT_FOUND
            });
          }
          return cb(null, {
            rc: v_codes.OK,
            api_url: PREFIX + proof_post.permalink + ".json",
            human_url: PREFIX + proof_post.permalink,
            remote_id: proof_post.name
          });
        };
      })(this));
    };

    RedditScraper.prototype.unpack_posts = function(json) {
      var data, posts, _i, _len, _ref1, _results;
      if (((json != null ? json.kind : void 0) === 'Listing') && ((posts = json != null ? (_ref1 = json.data) != null ? _ref1.children : void 0 : void 0) != null) && (posts.length === 0 || posts[0].kind === 't3')) {
        _results = [];
        for (_i = 0, _len = posts.length; _i < _len; _i++) {
          data = posts[_i].data;
          _results.push(data);
        }
        return _results;
      } else {
        return null;
      }
    };

    RedditScraper.prototype.unpack_post = function(json) {
      var parent, _ref1, _ref2, _ref3, _ref4, _ref5;
      if ((((_ref1 = json[0]) != null ? _ref1.kind : void 0) === 'Listing') && (((_ref2 = (parent = (_ref3 = json[0]) != null ? (_ref4 = _ref3.data) != null ? (_ref5 = _ref4.children) != null ? _ref5[0] : void 0 : void 0 : void 0)) != null ? _ref2.kind : void 0) === 't3')) {
        return parent.data;
      } else {
        return null;
      }
    };

    RedditScraper.prototype.check_post = function(_arg) {
      var body, line, lstrip, med_id, post, proof_text_check, username;
      post = _arg.post, username = _arg.username, proof_text_check = _arg.proof_text_check;
      med_id = proof_text_check_to_med_id(proof_text_check);
      if (!(((post != null ? post.subreddit : void 0) != null) && (post.author != null) && (post.selftext != null) && (post.title != null))) {
        return v_codes.CONTENT_MISSING;
      } else if (post.subreddit.toLowerCase() !== 'keybaseproofs') {
        return v_codes.SERVICE_ERROR;
      } else if (!sncmp(post.author, username)) {
        return v_codes.BAD_USERNAME;
      } else if (post.title.indexOf(med_id) < 0) {
        return v_codes.TITLE_NOT_FOUND;
      } else {
        lstrip = function(line) {
          var m;
          if ((m = line.match(/^\s+(.*?)$/)) != null) {
            return m[1];
          } else {
            return line;
          }
        };
        body = ((function() {
          var _i, _len, _ref1, _results;
          _ref1 = post.selftext.split("\n");
          _results = [];
          for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
            line = _ref1[_i];
            _results.push(lstrip(line));
          }
          return _results;
        })()).join("\n");
        if (body.indexOf(proof_text_check) < 0) {
          return v_codes.TEXT_NOT_FOUND;
        } else {
          return v_codes.OK;
        }
      }
    };

    RedditScraper.prototype.check_status = function(_arg, cb) {
      var api_url, err, json, post, proof_text_check, rc, remote_id, username, ___iced_passed_deferral, __iced_deferrals, __iced_k;
      __iced_k = __iced_k_noop;
      ___iced_passed_deferral = iced.findDeferral(arguments);
      username = _arg.username, api_url = _arg.api_url, proof_text_check = _arg.proof_text_check, remote_id = _arg.remote_id;
      (function(_this) {
        return (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/Users/max/src/keybase/proofs/src/scrapers/reddit.iced",
            funcname: "RedditScraper.check_status"
          });
          _this._get_url_body({
            url: api_url,
            json: true,
            qs: {
              cachebust: Math.random()
            }
          }, __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                rc = arguments[1];
                return json = arguments[2];
              };
            })(),
            lineno: 124
          }));
          __iced_deferrals._fulfill();
        });
      })(this)((function(_this) {
        return function() {
          rc = rc !== v_codes.OK ? rc : (post = _this.unpack_post(json)) == null ? v_codes.CONTENT_FAILURE : _this.check_post({
            post: post,
            username: username,
            proof_text_check: proof_text_check
          });
          return cb(err, rc);
        };
      })(this));
    };

    return RedditScraper;

  })(BaseScraper);

}).call(this);
