package Reddit::Client;

our $VERSION = '1.073'; # must be numeric, i.e. not 1.07.1
$VERSION = eval $VERSION;

use strict;
use warnings;
use Carp;

use Data::Dumper   qw/Dumper/;
use JSON           qw//;
use File::Spec     qw//;
use Digest::MD5    qw/md5_hex/;
use POSIX          qw/strftime/;
use File::Path::Expand qw//;

require Reddit::Client::Account;
require Reddit::Client::Comment;
require Reddit::Client::Link;
require Reddit::Client::SubReddit;
require Reddit::Client::Request;
require Reddit::Client::Message;

#===============================================================================
# Constants
#===============================================================================

use constant DEFAULT_LIMIT           => 25;

use constant VIEW_HOT                => '';
use constant VIEW_NEW                => 'new';
use constant VIEW_CONTROVERSIAL      => 'controversial';
use constant VIEW_TOP                => 'top';
use constant VIEW_RISING	     => 'rising';
use constant VIEW_DEFAULT            => VIEW_HOT;

use constant VOTE_UP                 => 1;
use constant VOTE_DOWN               => -1;
use constant VOTE_NONE               => 0;

use constant SUBMIT_LINK             => 'link';
use constant SUBMIT_SELF       	     => 'self';
use constant SUBMIT_MESSAGE          => 'message';

use constant MESSAGES_INBOX	     => 'inbox';
use constant MESSAGES_UNREAD	     => 'unread';
use constant MESSAGES_SENT	     => 'sent';
use constant MESSAGES_MESSAGES       => 'messages';
use constant MESSAGES_COMMENTREPLIES => 'comments';
use constant MESSAGES_POSTREPLIES    => 'selfreply';
use constant MESSAGES_MENTIONS	     => 'mentions';

use constant API_ME                  => 0;
use constant API_INFO                => 1;
use constant API_SEARCH              => 2;
use constant API_LOGIN               => 3;
use constant API_SUBMIT              => 4;
use constant API_COMMENT             => 5;
use constant API_VOTE                => 6;
use constant API_SAVE                => 7;
use constant API_UNSAVE              => 8;
use constant API_HIDE                => 9;
use constant API_UNHIDE              => 10;
use constant API_SUBREDDITS          => 11;
use constant API_LINKS_FRONT         => 12;
use constant API_LINKS_OTHER         => 13;
use constant API_DEL                 => 14;
use constant API_MESSAGE             => 15;
use constant API_COMMENTS_FRONT	     => 16;
use constant API_COMMENTS	     => 17;
use constant API_MESSAGES	     => 18;
use constant API_MARK_READ	     => 19;
use constant API_MARKALL	     => 20;
use constant API_MY_SUBREDDITS       => 21;

use constant SUBREDDITS_HOME         => '';
use constant SUBREDDITS_MINE         => 'subscriber';
use constant SUBREDDITS_POPULAR      => 'popular';
use constant SUBREDDITS_NEW          => 'new';
use constant SUBREDDITS_CONTRIB      => 'contributor';
use constant SUBREDDITS_MOD          => 'moderator';

#===============================================================================
# Parameters
#===============================================================================

our $DEBUG            = 0;
our $BASE_URL         = 'https://oauth.reddit.com';
use constant BASE_URL => 'https://oauth.reddit.com';
our $LINK_URL         = 'https://www.reddit.com';
use constant LINK_URL => 'https://www.reddit.com';
our $UA               = sprintf 'Reddit::Client/%f', $VERSION;

our @API;
$API[API_ME            ] = ['GET',  '/api/v1/me'            ];
$API[API_INFO          ] = ['GET',  '/api/info'             ];
$API[API_SEARCH        ] = ['GET',  '/subreddits/search'    ];
$API[API_LOGIN         ] = ['POST', '/api/login/%s'         ];
$API[API_SUBMIT        ] = ['POST', '/api/submit'           ];
$API[API_COMMENT       ] = ['POST', '/api/comment'          ];
$API[API_VOTE          ] = ['POST', '/api/vote'             ];
$API[API_SAVE          ] = ['POST', '/api/save'             ];
$API[API_UNSAVE        ] = ['POST', '/api/unsave'           ];
$API[API_HIDE          ] = ['POST', '/api/hide'             ];
$API[API_UNHIDE        ] = ['POST', '/api/unhide'           ];
$API[API_SUBREDDITS    ] = ['GET',  '/subreddits/%s'        ];
$API[API_MY_SUBREDDITS ] = ['GET',  '/subreddits/mine/%s'   ];
$API[API_LINKS_OTHER   ] = ['GET',  '/%s'                   ];
$API[API_LINKS_FRONT   ] = ['GET',  '/r/%s/%s'              ];
$API[API_DEL           ] = ['POST', '/api/del'              ];
$API[API_MESSAGE       ] = ['POST', '/api/compose'          ];
$API[API_COMMENTS      ] = ['GET',  '/r/%s/comments'        ];
$API[API_COMMENTS_FRONT] = ['GET',  '/comments'             ];
$API[API_MESSAGES      ] = ['GET',  '/message/%s'           ];
$API[API_MARK_READ     ] = ['POST', '/api/read_message'     ];
$API[API_MARKALL       ] = ['POST', '/api/read_all_messages'];
#===============================================================================
# Package routines
#===============================================================================

sub DEBUG {
    if ($DEBUG) {
        my ($format, @args) = @_;
        my $ts  = strftime "%Y-%m-%d %H:%M:%S", localtime;
        my $msg = sprintf $format, @args;
        chomp $msg;
        printf STDERR "[%s] [ %s ]\n", $ts, $msg;
    }
}

sub subreddit {
    my $subject = shift;
    $subject =~ s/^\/r//; # trim leading /r
    $subject =~ s/^\///;  # trim leading slashes
    $subject =~ s/\/$//;  # trim trailing slashes

    if ($subject !~ /\//) {   # no slashes in name - it's probably good
        if ($subject eq '') { # front page
            return '';
        } else {              # subreddit
            return $subject;
        }
    } else { # fail
        return;
    }
}

#===============================================================================
# Class methods
#===============================================================================

use fields (
    	'modhash',      # store session modhash
    	'cookie',       # store user cookie
    	'session_file', # path to session file
    	'user_agent',   # user agent string
    	'token',	# oauth authorization token
    	'tokentype',    # unused but saved for reference
    	'last_token',	# time last token was acquired
    	'client_id',	# These 4 values saved for automatic token refreshing
    	'secret',
	'username',
	'password',
);

sub new {
    my ($class, %param) = @_;
    my $self = fields::new($class);

    if (not exists $param{user_agent}) {
        carp "Reddit::Client->new: user_agent required in future version.";
        $param{user_agent} = $UA;
    }
    $self->{user_agent} = $param{user_agent};

	if ($param{username} || $param{password} || $param{client_id} || $param{secret}) {
		if (!$param{username} || !$param{password} || !$param{client_id} || !$param{secret}) {
			croak "If any of username, password, client_id, or secret are provided, all are required.";
		} else {
			$self->get_token(
					client_id	=> $param{client_id},
					secret		=> $param{secret},
					username	=> $param{username},
					password	=> $param{password},	
			);
		}
	}

    return $self;
}

sub version {
	my $self = shift;
	return $VERSION;
}

#===============================================================================
# Internal management
#===============================================================================

sub request {
    my ($self, $method, $path, $query, $post_data) = @_;

	if (!$self->{last_token} || $self->{last_token} <= time - 3598) {
		$self->get_token(client_id=>$self->{client_id}, secret=>$self->{secret}, username=>$self->{username}, password=>$self->{password});
	}

    # Trim leading slashes off of the path
    $path =~ s/^\/+//;
    my $request = Reddit::Client::Request->new(
        user_agent => $self->{user_agent},
        url        => sprintf('%s/%s', $BASE_URL, $path),
        method     => $method,
        query      => $query,
        post_data  => $post_data,
        modhash    => $self->{modhash},
        cookie     => $self->{cookie},
	token	   => $self->{token},
	tokentype  => $self->{tokentype},
    );

    return $request->send;
}

sub get_token {
	my ($self, %param) = @_;
	$self->{client_id} 	= $param{client_id} || croak "need client_id"; 
	$self->{secret} 	= $param{secret}    || croak "need secret";
	$self->{username}	= $param{username}  || croak "need username";
	$self->{password}	= $param{password}  || croak "need password";
	$self->{last_token} 	= time;

	my $message = Reddit::Client::Request->token_request($self->{client_id}, $self->{secret}, $self->{username}, $self->{password}, $self->{user_agent});
	my $j = JSON::decode_json($message);
	$self->{token} 		= $j->{access_token};
	$self->{tokentype} 	= $j->{token_type};

	if (!$self->{token}) { croak "Unable to get or parse token."; }
}

sub has_token {
	my $self = shift;
	return (!$self->{last_token} || $self->{last_token} <= time - 3598) ? 0 : 1;
}

sub json_request {
    my ($self, $method, $path, $query, $post_data) = @_;
    DEBUG('%4s JSON', $method);

    if ($method eq 'POST') {
        $post_data ||= {};
        $post_data->{api_type} = 'json';
    } else { 
        #$path .= '.json'; # the oauth api returns json by default
    }

    my $response = $self->request($method, $path, $query, $post_data);
	#use Data::Dump::Color;
	#dd $response;
    my $json     = JSON::from_json($response);

    if (ref $json eq 'HASH' && $json->{json}) {
        my $result = $json->{json};
        if (@{$result->{errors}}) {
            DEBUG('API Errors: %s', Dumper($result->{errors}));
            my @errors = map {
                sprintf '[%s] %s', $_->[0], $_->[1]
            } @{$result->{errors}};
            croak sprintf("Error(s): %s", join('|', @errors));
        } else {
            return $result;
        }
    } else {
        return $json;
    }
}

sub api_json_request {
    my ($self, %param) = @_;
    my $args     = $param{args} || [];
    my $api      = $param{api};
    my $data     = $param{data};
    my $callback = $param{callback};

    croak 'Expected "api"' unless defined $api;

    DEBUG('API call %d', $api);

    my $info   = $API[$api] || croak "Unknown API: $api";
    my ($method, $path) = @$info;
    $path = sprintf $path, @$args;

    my ($query, $post_data);
    if ($method eq 'GET') {
        $query = $data;
    } else {
        $post_data = $data;
    }

    my $result = $self->json_request($method, $path, $query, $post_data);
	#use Data::Dump::Color;
	#dd $result;

    if (exists $result->{errors}) {
        my @errors = @{$result->{errors}};

        if (@errors) {
            DEBUG("ERRORS: @errors");
            my $message = join(' | ', map { join(', ', @$_) } @errors);
            croak $message;
        }
    }
	#use Data::Dump::Color;
	#dd $result;

    if (defined $callback && ref $callback eq 'CODE') {
        return $callback->($result);
    } else {
        return $result;
    }
}

# deprecated, to be removed
sub is_logged_in {
    return defined $_[0]->{modhash};
}

# deprecated, to be removed
sub require_login {
    my $self = shift;
    return;
}


#===============================================================================
# User and account management
#===============================================================================

sub me {
    my $self = shift;
    DEBUG('Request user account info');
    my $result = $self->api_json_request(api => API_ME);
    #return Reddit::Client::Account->new($self, $result->{data});
    return Reddit::Client::Account->new($self, $result);
}

sub list_subreddits {
    	my ($self, %param) = @_;

	my $type = $param{view} || SUBREDDITS_HOME;
    	my $query  = {};
        $query->{before} = $param{before} if $param{before};
        $query->{after}  = $param{after}  if $param{after};
	if (exists $param{limit}) { $query->{limit} = $param{limit} || 500; }
	else 			  { $query->{limit} = DEFAULT_LIMIT;	    }
    DEBUG('List subreddits [%s]', $type);
    defined $type || croak 'Expected $type"';
	my $api = $type eq SUBREDDITS_MOD || $type eq SUBREDDITS_CONTRIB || $type eq SUBREDDITS_MINE ? API_MY_SUBREDDITS : API_SUBREDDITS; 

    my $result = $self->api_json_request(
	api => $api, 
	args => [$type],
	data => $query,
    );
    return [
        map {Reddit::Client::SubReddit->new($self, $_->{data})} @{$result->{data}{children}}
    ];
}

sub contrib_subreddits { 
	my ($self, %param) = @_;
	$param{view} = SUBREDDITS_CONTRIB;	
	return $_[0]->list_subreddits(%param);
}
sub home_subreddits    { 
	my ($self, %param) = @_;
	$param{view} = SUBREDDITS_HOME;
	return $_[0]->list_subreddits(%param);
}
sub mod_subreddits     { 
	my ($self, %param) = @_;
	$param{view} = SUBREDDITS_MOD;
	return $_[0]->list_subreddits(%param);
}
sub my_subreddits      { 
	my ($self, %param) = @_;
	$param{view} = SUBREDDITS_MINE;
	return $_[0]->list_subreddits(%param);
}
sub new_subreddits     { 
	my ($self, %param) = @_;
	$param{view} = SUBREDDITS_NEW;
	return $_[0]->list_subreddits(%param);
}
sub popular_subreddits { 
	my ($self, %param) = @_;
	$param{view} = SUBREDDITS_POPULAR;
	return $_[0]->list_subreddits(%param);
}

#===============================================================================
# Inbox and messages
#===============================================================================
sub get_inbox {
	my ($self, %param) = @_;
    	my $limit     	= $param{limit}		|| DEFAULT_LIMIT;
	my $mode	= $param{mode}		|| MESSAGES_INBOX;	
	my $view	= $param{view}		|| MESSAGES_INBOX;

	# this before and after business is stupid and needs to be fixed
	# in 3 separate places
	my $query = {};
	$query->{mark}   = $param{mark} ? 'true' : 'false';
	$query->{sr_detail} = $param{sr_detail} if $param{sr_detail};
        $query->{before} = $param{before} if $param{before};
        $query->{after}  = $param{after}  if $param{after};
	if (exists $param{limit}) { $query->{limit} = $param{limit} || 500; }
	else 			  { $query->{limit} = DEFAULT_LIMIT;	    }
	
	my $result = $self->api_json_request(
		api	=> API_MESSAGES,
		args	=> [$view],
		data	=> $query,
	);

	return [
		map { Reddit::Client::Message->new($self, $_->{data}) } @{$result->{data}{children}}
	];
}

# TODO
sub mark_read {
	my ($self, %param) = @_;

}

sub mark_inbox_read {
	my $self = shift;
	my ($method, $path) = @{$API[API_MARKALL]};
	my $post_data = {api_type=>'json'};
	my $result = $self->request($method, $path, {}, $post_data);
}

#===============================================================================
# Finding subreddits and listings
#===============================================================================

sub info {
    my ($self, $id) = @_;
    DEBUG('Get info for id %s', $id);
    defined $id || croak 'Expected $id';
    my $query->{id} = $id;
    
    my $info = $self->api_json_request(
	api => API_INFO, 
	args => [$id], 
	data=>$query);
    my $rtn = $info->{data}->{children}[0]->{data};
    $rtn->{kind} = $info->{data}->{children}[0]->{kind} if $rtn;
    return $rtn;
}

sub get_permalink {
	# commentid is short id
	# post_fullname is because we need to get the post to get its permalink
	my ($self, $commentid, $post_fullname) = @_;
	my $info = $self->info($post_fullname);
	return sprintf "%s%s%s", $LINK_URL, $info->{permalink}, $commentid;
}

sub find_subreddits {
    	my ($self, %param) = @_;
	#defined $query || croak 'Expected $query';
	#DEBUG('Search subreddits: %s', $query);

    	my $query  = {};
	$query->{q} = $param{q} || croak "expected 'query'";
        $query->{before} = $param{before} if $param{before};
        $query->{after}  = $param{after}  if $param{after};
	if (exists $param{limit}) { $query->{limit} = $param{limit} || 500; }
	else 			  { $query->{limit} = DEFAULT_LIMIT;	    }

	# sort
	$query->{sort} = $param{sort} || 'relevance';

    	my $result = $self->api_json_request(
		api => API_SEARCH, 
		data => $query,
	);
    	return [
        	map {Reddit::Client::SubReddit->new($self, $_->{data})} @{$result->{data}{children}}
    	];
}

sub fetch_links {
    my ($self, %param) = @_;
    my $subreddit = $param{subreddit} || '';
    my $view      = $param{view}      || VIEW_DEFAULT;
    #DEBUG('Fetch %d link(s): %s/%s?before=%s&after=%s', $limit, $subreddit, $view, ($before || '-'), ($after || '-'));

    	my $query  = {};
        $query->{before} = $param{before} if $param{before};
        $query->{after}  = $param{after}  if $param{after};
	if (exists $param{limit}) { $query->{limit} = $param{limit} || 500; }
	else 			  { $query->{limit} = DEFAULT_LIMIT;	    }

    $subreddit = subreddit($subreddit);

    my $args = [$view];
    unshift @$args, $subreddit if $subreddit;

    my $result = $self->api_json_request(
        api      => ($subreddit ? API_LINKS_FRONT : API_LINKS_OTHER),
        args     => $args,
        data     => $query,
    );

    return [
        map {Reddit::Client::Link->new($self, $_->{data})} @{$result->{data}{children}} 
    ];
}

# alias for fetch_links to make naming convention consistent
sub get_links {
    	my ($self, %param) = @_;
	return $self->fetch_links(%param);
}

sub get_link {
    	my ($self, $fullname) = @_;
	if (	!$fullname || 
		length($fullname) < 8 ||
		substr($fullname, 0, 2) ne "t3")
	{ croak "expected link fullname (i.e. t3_3ng7r5)";	}

	my $info = $self->info($fullname);

	return $info if !$info;
	return Reddit::Client::Link->new($self, $info);
}

sub get_comment {
    	my ($self, $fullname) = @_;
	if (	!$fullname || 
		length($fullname) < 8 ||
		substr($fullname, 0, 2) ne "t1")
	{ croak "expected comment fullname (i.e. t1_cvp5afk)"; }

	my $info = $self->info($fullname);

	return $info if !$info;
	return Reddit::Client::Comment->new($self, $info);
}

sub get_subreddit_comments {
	my ($self, %param) = @_;
	my $subreddit 	= $param{subreddit} 	|| '';
	my $view 	= $param{view} 		|| VIEW_DEFAULT;

	my $query = {};
        $query->{before} = $param{before} if $param{before};
        $query->{after}  = $param{after}  if $param{after};
	if (exists $param{limit}) { $query->{limit} = $param{limit} || 500; }
	else 			  { $query->{limit} = DEFAULT_LIMIT;	    }

	$subreddit = subreddit($subreddit); # remove slashes and leading r/
    	my $args = [$view];
    	unshift @$args, $subreddit if $subreddit;

    	my $result = $self->api_json_request(
        	api      => ($subreddit ? API_COMMENTS : API_COMMENTS_FRONT),
        	args     => $args,
        	data     => $query,
    	);

    	return [
        	 map {Reddit::Client::Comment->new($self, $_->{data})} @{$result->{data}{children}} 
    	];
}

#===============================================================================
# Deleting stories or comments
#===============================================================================

# TODO unit test
sub delete {
    my ($self, $name) = @_;
    croak 'Expected $fullname' if !$name;
    my $type = substr $name, 0, 2;
    croak '$fullname must be a post or comment' if $type ne 't1' && $type ne 't3';

    DEBUG('Delete post/comment %s', $name);

    my $result = $self->api_json_request(api => API_DEL, data => { id => $name });
    return 1;
}

#===============================================================================
# Submitting links
#===============================================================================

sub submit_link {
    my ($self, %param) = @_;
    my $subreddit = $param{subreddit} || '';
    my $title     = $param{title}     || croak 'Expected "title"';
    my $url       = $param{url}       || croak 'Expected "url"';
	my $replies = exists $param{inbox_replies} ? $param{inbox_replies} : 1;

    DEBUG('Submit link to %s: %s', $subreddit, $title, $url);

    $subreddit = subreddit($subreddit);

    my $result = $self->api_json_request(api => API_SUBMIT, data => {
        title    => $title,
        url      => $url,
        sr       => $subreddit,
        kind     => SUBMIT_LINK,
	sendreplies=>$replies,
    });

    return $result->{data}{name};
}

sub submit_text {
    my ($self, %param) = @_;
    my $subreddit = $param{subreddit} || '';
    my $title     = $param{title}     || croak 'Expected "title"';
    my $text      = $param{text}      || croak 'Expected "text"';
	my $replies = exists $param{inbox_replies} ? $param{inbox_replies} : 1;

    DEBUG('Submit text to %s: %s', $subreddit, $title);

    $subreddit = subreddit($subreddit);

    my $result = $self->api_json_request(api => API_SUBMIT, data => {
        title    => $title,
        text     => $text,
        sr       => $subreddit,
        kind     => SUBMIT_SELF,
	sendreplies=>$replies,
    });

    return $result->{data}{name};
}

#===============================================================================
# Comments
#===============================================================================

sub get_comments { # currently broken
    my ($self, %param) = @_;
    my $permalink = $param{permalink} || croak 'Expected "permalink"';

    DEBUG('Retrieve comments for %s', $permalink);

    my $result   = $self->json_request('GET', $permalink);
    my $comments = $result->[1]{data}{children};
    return [ map { Reddit::Client::Comment->new($self, $_->{data}) } @$comments ];
}

sub submit_comment {
    my ($self, %param) = @_;
    my $parent_id = $param{parent_id} || croak 'Expected "parent_id"';
    my $comment   = $param{text}      || croak 'Expected "text"';

    croak '$fullname must be a post or comment' if !$self->ispost($parent_id) && !$self->iscomment($parent_id);
    DEBUG('Submit comment under %s', $parent_id);

    my $result = $self->api_json_request(api => API_COMMENT, data => {
        thing_id => $parent_id,
        text     => $comment,
    });

    return $result->{data}{things}[0]{data}{id};
}

#===============================================================================
# Private messages
#===============================================================================

sub send_message {
    	my ($self, %param) = @_;
	my $to		= $param{to}	 	|| croak 'Expected "to"';
	my $subject	= $param{subject}	|| croak 'Expected "subject"';
	my $text	= $param{text}		|| croak 'Expected "text"';

	croak '"subject" cannot be longer than 100 characters' if length $subject > 100;
    	
	#$self->require_login;
    	DEBUG('Submit message to %s: %s', $to, $subject);

    	my $result = $self->api_json_request(api => API_MESSAGE, data => {
       	 to    		=> $to,
       	 subject  	=> $subject,
       	 text		=> $text,
       	 kind   	=> SUBMIT_MESSAGE,
    	});

	return $result;
}

#===============================================================================
# Voting
#===============================================================================

sub vote {
    my ($self, $name, $direction) = @_;
    defined $name      || croak 'Expected $name';
    defined $direction || croak 'Expected $direction';
    croak '$fullname must be a post or comment' if !$self->ispost($name) && !$self->iscomment($name);
    croak 'Invalid vote direction' unless "$direction" =~ /^(-1|0|1)$/;
    DEBUG('Vote %d for %s', $direction, $name);
    $self->api_json_request(api => API_VOTE, data => { dir => $direction, id  => $name });
}

#===============================================================================
# Saving and hiding
#===============================================================================

sub save {
    my $self = shift;
    my $name = shift || croak 'Expected $fullname';
    croak '$fullname must be a post or comment' if !$self->ispost($name) && !$self->iscomment($name);
    DEBUG('Save %s', $name);
    $self->api_json_request(api => API_SAVE, data => { id => $name });
}

sub unsave {
    my $self = shift;
    my $name = shift || croak 'Expected $fullname';
    croak '$fullname must be a post or comment' if !$self->ispost($name) && !$self->iscomment($name);
    DEBUG('Unsave %s', $name);
    $self->api_json_request(api => API_UNSAVE, data => { id => $name });
}

sub hide {
    my $self = shift;
    my $name = shift || croak 'Expected $fullname';
    croak '$fullname must be a post' if !$self->ispost($name);
    DEBUG('Hide %s', $name);
    $self->api_json_request(api => API_HIDE, data => { id => $name });
}

sub unhide {
    my $self = shift;
    my $name = shift || croak 'Expected $fullname';
    croak '$fullname must be a post' if !$self->ispost($name);
    DEBUG('Unhide %s', $name);
    $self->api_json_request(api => API_UNHIDE, data => { id => $name });
}


# Internal

sub ispost {
	my ($self, $name) = @_;
    	my $type = substr $name, 0, 2;
	return $type eq 't3';
}

sub iscomment {
	my ($self, $name) = @_;
    	my $type = substr $name, 0, 2;
	return $type eq 't1';
}

1;

__END__

=pod

=head1 NAME

Reddit::Client - A Perl wrapper for the Reddit API.

The official documentation can be found at L<http://redditclient.readthedocs.org/en/latest/>.

=head1 SYNOPSIS

    use Reddit::Client;

    my $client_id  	= "DFhtrhBgfhhRTd";
    my $secret     	= "KrDNsbeffdbILOdgbgSvSBsbfFs";
    my $username   	= "reddit_username";
    my $password   	= "reddit_password";


    # Create a Reddit::Client object and authorize in one step
    my $reddit = new Reddit::Client(
	user_agent 	=> 'MyScriptName 0.5 by /u/earth-tone',
	client_id	=> $client_id,
	secret		=> $secret,
	username	=> $username,
	password	=> $password,
    );
	
    # Or create object then authorize.
    # Useful if you need to switch between accounts, for example if you were to check the inboxes of several accounts.
    my $reddit = Reddit::Client->new(
        user_agent   	=> 'MyApp/1.0 by /u/earth-tone',
    );

    $reddit->get_token(
	client_id	=> $client_id,
	secret		=> $secret,
	username	=> $username,
	password	=> $password,
    );

    # Check your inbox
    my $me = $reddit->me();
    print "You've got mail!" if $me->{has_mail};

    # Submit a link
    $reddit->submit_link(
        subreddit 	=> 'test',
        title     	=> 'Perl is still alive!',
        url       	=> 'http://www.perl.org'
    );

    # Submit a text post
    $reddit->submit_text(
	subreddit 	=> 'test',
	title		=> 'my test',
	text		=> 'a test'
    );

    # Get posts from a subreddit or multi
    my $posts = $reddit->fetch_links(subreddit=>'test', limit=>5);
    foreach my $post (@$posts) {
	print $post->{title} . "\n";
	if (!$post->{is_self}) { # Is it a self post or a link?
		print $post->{url};
	} else {
		print $post->{selftext};
	}
    }

    # Get comments from a subreddit or multi
    my $cmts = $reddit->get_subreddit_comments('test');
    foreach my $cmt (@$cmts) {
	print "$cmt->{author} says: $cmt->{body}\n";
    }


=head1 DESCRIPTION

Reddit::Client provides methods and object wrappers for objects exposed
by the Reddit API. This module handles HTTP communication, oauth session management, and communication with Reddit's external API. For more information about the Reddit API, see L<https://github.com/reddit/reddit/wiki/API>.

Beginning August 3rd, 2015, the Reddit API requires Oauth authentication. This amounts to two extra arguments at the beginning of your script; in exchange you you twice as many requests per minute as before (60 vs 30) and some added convenience on the back end.

To get Oauth keys, visit your apps page: L<https://www.reddit.com/prefs/apps>. Choose a "script" type app. None of the other fields are needed for a script type app; you can put in C<127.0.0.1> for the URLs or whatever you like.

Every account that uses this script must have permission to use it. So for example if you were to check the inboxes of your various accounts, each one would need permission. To add accounts click "add developer" on the right, after you've created the app.

=head1 CONSTANTS

    VIEW_HOT            "Hot" links feed
    VIEW_NEW            "New" links feed
    VIEW_RISING		"Rising" links feed
    VIEW_CONTROVERSIAL  "Controversial" links feed
    VIEW_TOP            "Top" links feed

    VIEW_DEFAULT        Default feed if not specified (VIEW_HOT)
    DEFAULT_LIMIT       The default number of links to be retried (25)

    VOTE_UP             Up vote
    VOTE_DOWN           Down vote
    VOTE_NONE           Remove any vote

    SUBREDDITS_HOME     List reddits on the homepage
    SUBREDDITS_POPULAR  List popular reddits
    SUBREDDITS_NEW      List new reddits
    SUBREDDITS_MINE     List reddits for which the logged in user is subscribed
    SUBREDDITS_CONTRIB  List reddits for which the logged in user is a contributor
    SUBREDDITS_MOD      List reddits for which the logged in user is a moderator

=head1 GLOBALS

=over


=item $DEBUG

When set to true, outputs a small amount of debugging information.


=back

=head1 SUBROUTINES/METHODS

=over

=item new(user_agent => ... [, client_id =>, secret =>, username=>, password =>])

Creates a new Reddit::Client object. Optionally authenticates at the same time. If any of the four optional arguments are used, all are required.


=item get_token(client_id =>, secret =>, username=>, password =>)

Get an Oauth token from Reddit. The client ID and secret come  from your apps page, where you will first have to register the script: L<https://www.reddit.com/prefs/apps>. Only the account that created the app and accounts that are registered as developers for the app will be able to use it. 

For a Perl script, select a "script" type app. The "about url" and "redirect uri" can be any address; they are not used for scripts. 

 
=item has_token

Return true if a valid Oauth token exists.


=item me

Returns a Reddit::Client::Account object.

=item mark_all_read

Mark your inbox read. May not happen instantly.


=item info($fullname)

Returns a hash of extended information about C<$fullname>. Contains some information not available elsewhere.


=item list_subreddits($type)

Returns a list of Reddit::Client::SubReddit objects for C<$type>, where C<$type>
is a C<SUBREDDITS_*> constant. A number of alias functions are available:


=over 4

=item my_subreddits

Alias for C<list_subreddits(SUBREDDITS_MINE)>. 


=item home_subreddits

Alias for C<list_subreddits(SUBREDDITS_HOME)>. 


=item mod_subreddits

Alias for C<list_subreddits(SUBREDDITS_MOD)>. 


=item contrib_subreddits

Alias for C<list_subreddits(SUBREDDITS_CONTRIB)>.


=item popular_subreddits

Alias for C<list_subreddits(SUBREDDITS_POPULAR)>.


=item new_subreddits

Alias for C<list_subreddits(SUBREDDITS_NEW)>.

=back


=item find_subreddits($query)

Returns a list of SubReddit objects matching C<$query>.


=item fetch_links([subreddit => ...], [view => ...], [limit => ...], [before => ...], [after => ...])

Returns a list of Link objects. 

All arguments are optional. If C<subreddit> is specified,
the list of links is returned from the desired subreddit or multi (i.e. "pics+new"). Otherwise, the
links will be from the front page of the authenticated user (i.e. what you would see as the front page if you logged in as that user) . C<view> specifieds the feed (e.g.
C<VIEW_NEW> or C<VIEW_HOT>). C<limit> may be used to limit the number of
objects returned; Reddit returns a maximum of 100. C<before> and C<after> denote the placeholders for
slicing the feed up, just as the reddit urls themselves do. Data is returned
as a hash with three keys, I<before>, I<after>, and I<items>.


=item delete(name => ...)

Deletes a post or comment. The object's fullname is required.


=item submit_link(subreddit => ..., title => ..., url => ... [inbox_replies => ...])

Submits a link to a reddit. Returns the fullname of the new link. If inbox_replies is set and is false, disable inbox replies for that post.


=item submit_text(subreddit => ..., title => ..., text => ... [inbox_replies => ...)

Submits a self-post to a reddit. Returns the fullname of the new post. If inbox_replies is set and is false, disable inbox replies for that post.
 

=item get_subreddit_comments([subreddit => ...][before => ...][after => ...][limit => ...])

Return a list of Reddit::Client::Comment objects from a subreddit or multi. All arguments are optional. If subreddit is ommitted, a multi of the subscribed subreddits from the authenticating account will be returned (i.e. what you see when you visit reddit.com's from page and are logged in). If limit is ommitted, Reddit's default limit of 25 is used. If limit is present but false, this is interpreted as no limit and the maximum is returned (100).


=item submit_comment(parent_id => ..., text => ...)

Submits a new comment underneath C<parent_id>. C<parent_id> must be a fullname.


=item vote(item_id => ..., direction => ...)

Votes for C<item_id>. C<direction> is one of C<VOTE_UP>, C<VOTE_DOWN>,
or C<VOTE_NONE>. C<item_id> must be a fullname.


=item save($item_id)

Saves C<$item_id> under the user's account. C<item_id> must be a fullname.


=item unsave($item_id)

Unsaves C<$item_id> under the user's account. C<item_id> must be a fullname.


=item hide($item_id)

Hides $<item_id>. Throws an error if the user does not have permission to hide
the item in question. C<item_id> must be a fullname.


=item unhide($item_id)

Unhides $<item_id>. Throws an error if the user does not have permission to
unhide the item in question. C<item_id> must be a fullname.


=back

=head1 INTERNAL ROUTINES

=over

=item DEBUG

When C<$Reddit::Client::DEBUG> is true, acts as syntactic sugar for
warn(sprintf(@_)). Used to provided logging.



=item subreddit

Strips slashes and leading /r from a subreddit to ensure that only
the "display name" of the subreddit is returned.


=item request

Performs a request to reddit's servers using LWP. If the user is
logged in, adds the "uh" and "modhash" parameters to POST queries
as well as adding the reddit-specified cookie value for reddit_session.


=item json_request

Wraps C<request>, configuring the parameters to perform the request
with an api_type of "json". After the request is complete, parses the
JSON result and throws and error if one is specified in the result
contents. Otherwise, returns the json data portion of the result.

=item    get_permalink

=item    get_token

=item    send_message

=item api_json_request

Wraps C<json_request>, getting method and path from an API_CONSTANT.


=back

=head1 AUTHOR

L<mailto:earth-tone@ubwg.net>


=head1 LICENSE

BSD license

=cut
