package Cuitter::Plugin::OAuth;
use Mouse::Role;
use WWW::Mechanize;
use Encode;

requires qw( client cache input output tweet );

sub _init_OAuth {}

around _client_init => sub {
    my ( $next, $self, %arg ) = @_;
    %arg = ( %arg, consumer_key => 'wiTpiLrJ4K2jAqJfU5kfA', consumer_secret => 'mTvUUg5KEwrMG77nYryMU2Xoou4Yw11hO5tUjb8M9Jc' );
    delete $arg{ netrc };
    $self->$next( %arg );
    $self->load_oauth_tokens;
    unless( $self->client->authorized ) {
        my $account = $self->cache->get( 'account' );
        if ( !$account ) {
            $self->output->print( "Twitter account : " ) ;
            $account = $self->input->getline;
        }
        $self->output->print( "Twitter password : " );
        my $password = $self->input->getline;
        chomp $account;
        chomp $password;
        my $mech = WWW::Mechanize->new( agent => $self->client->{ useragent } );
        $mech->get( $self->client->get_authorization_url );
        die 'Twitter is down' unless $mech->success;
        $mech->form_id( 'login_form' );
        $mech->field( 'session[username_or_email]', $account );
        $mech->field( 'session[password]', $password );
        $mech->click_button( number => 2 );
        die 'Twitter is down' unless $mech->success;
        my ( $pin ) = $mech->content =~ /<div id=\"oauth_pin\">\n +?([0-9]{7})\n<\/div>/;
        my ( $access_token, $access_token_secret, $user_id, $screen_name ) = $self->client->request_access_token( verifier => $pin );
        $self->save_oauth_tokens( access_token => $access_token, access_token_secret => $access_token_secret );
        $self->cache->set( 'account', $user_id );
        $self->cache->set( 'username', $screen_name );
    }
    $self->username( $self->cache->get( 'username' ) );
};

around tweet => sub {
    my ( $next, $self, $line ) = @_;
    $line = decode( 'utf8', $line ) if $line;
    $self->$next( $line );
};

sub save_oauth_tokens {
    my ( $self, %arg ) = @_;
    $self->cache->set( $_, $arg{ $_ } ) for qw( access_token access_token_secret );
}

sub load_oauth_tokens {
    my $self = shift;
    $self->client->access_token( $self->cache->get( 'access_token' ) );
    $self->client->access_token_secret( $self->cache->get( 'access_token_secret' ) );
}

no Mouse::Role;
1;
__END__

=head1 NAME

Cuitter::Plugin::OAuth - a Cuitter Plugin

=head1 SYNOPSIS

This plugin needed by Cuitter since version 0.001003

=head1 DESCRIPTION

Cuitter loads this plugin automatically.

To use OAuth for login, this plugin changes operation. 

=head1 AUTHOR

Satoshi Azuma E<lt>ytnobody@gmail.comE<gt>

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

