//
//  ICFViewController.m
//  SocialNetworking
//
//  Created by Kyle Richter on 9/1/12.
//  Copyright (c) 2012 Kyle Richter. All rights reserved.
//

#import "ICFViewController.h"
#import "ICFTimelineViewController.h"

#define kActionSheetTwitter 1
#define kActionSheetFacebook 2

@implementation ICFViewController

@synthesize attachmentImage;
@synthesize facebookAccount;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    ACAccountStore *accountStore = [[ACAccountStore alloc] init];
    ACAccountType *facebookAccountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
    
    NSDictionary *options = @{
    ACFacebookAudienceKey : ACFacebookAudienceEveryone,
    ACFacebookAppIdKey : @"363120920441086",
    ACFacebookPermissionsKey : @[@"email"]};
    
    [accountStore requestAccessToAccountsWithType:facebookAccountType options:options completion:^(BOOL granted, NSError *error)
     {
         if (granted)
         {
             NSLog(@"Basic access granted");
         }
         
         else
         {
             NSLog(@"Basic access denied");
         }
     }];

    
    [socialTextView setDelegate: self];
    [socialTextView becomeFirstResponder];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(actionSheet.tag == kActionSheetFacebook)
    {
        ACAccountStore *accountStore = [[ACAccountStore alloc] init];
        ACAccountType *facebookAccountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
        NSDictionary *options = nil;
        
        NSLog(@"Publish permission granted");
        NSLog(@"Publish permission denied");

        switch (buttonIndex)
        {
            case 0:
                [self facebookComposer];
                break;
            case 1:
                options = @{
                ACFacebookAudienceKey : ACFacebookAudienceEveryone,
                ACFacebookAppIdKey : @"363120920441086",
                ACFacebookPermissionsKey : @[@"publish_stream"]};

                [accountStore requestAccessToAccountsWithType:facebookAccountType options:options completion:^(BOOL granted, NSError *error)
                 {
                     if (granted)
                     {
                         NSArray *accounts = [accountStore accountsWithAccountType:facebookAccountType];
                         self.facebookAccount = [accounts lastObject];
                         
                         [self performSelectorOnMainThread:@selector(facebookPost) withObject:nil waitUntilDone:NO];
                     }
                     
                     else
                     {
                         [self performSelectorOnMainThread:@selector(faceBookError:) withObject:error waitUntilDone:NO]; 
                     }
                 }];
                break;
            case 2:
                options = @{
                ACFacebookAudienceKey : ACFacebookAudienceEveryone,
                ACFacebookAppIdKey : @"363120920441086",
                ACFacebookPermissionsKey : @[@"read_stream"]};
                
                [accountStore requestAccessToAccountsWithType:facebookAccountType options:options completion:^(BOOL granted, NSError *error)
                 {
                     if (granted)
                     {
                         NSArray *accounts = [accountStore accountsWithAccountType:facebookAccountType];
                         self.facebookAccount = [accounts lastObject];
                         
                         [self performSelectorOnMainThread:@selector(facebookTimeline) withObject:nil waitUntilDone:NO];
                     }
                     
                     else
                     {
                         [self performSelectorOnMainThread:@selector(faceBookError:) withObject:error waitUntilDone:NO];
                     }
                 }];

                break;
            default:
                break;
        }
    }
    
    else if (actionSheet.tag == kActionSheetTwitter)
    {
        switch (buttonIndex)
        {
            case 0:
                [self twitterComposer];
                break;
            case 1:
                [self twitterPost];
                break;
            case 2:
                [self twitterTimeline];
                break;
            default:
                break;
        }
    }
}

- (IBAction)facebookAction:(id)sender
{
    
    [self performSelectorOnMainThread:@selector(showFacebookActionSheet) withObject:nil waitUntilDone:NO];
}

-(void)faceBookError:(NSError *)error
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
    [alert show];
    [alert release];
}


-(void)showFacebookActionSheet
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Facebook Actions" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Composer", @"Auto-Post", @"Timeline", nil];
    actionSheet.tag = kActionSheetFacebook;
    [actionSheet showInView: self.view];
    [actionSheet release];
    
    
}

-(void)facebookComposer
{
    if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
    {
        
        SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
        
        SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){
            if (result == SLComposeViewControllerResultCancelled)
            {
                NSLog(@"Cancelled");                
            }
            else
            {
                NSLog(@"Done");
            }
            
            [controller dismissViewControllerAnimated:YES completion:^(){
                [socialTextView becomeFirstResponder];
            }];
        };
        
        controller.completionHandler = myBlock;
        
        [controller setInitialText:socialTextView.text];
        
        [self presentViewController:controller animated:YES completion:nil];
    }
    
    else
    {
        NSLog(@"UnAvailable");
    }
}


-(void)facebookPost
{    
    NSDictionary *parameters = [NSDictionary dictionaryWithObject:socialTextView.text forKey:@"message"];
    
    NSURL *feedURL = nil;
    
    if(self.attachmentImage)
    {
        feedURL = [NSURL URLWithString:@"https://graph.facebook.com/me/photos"];
    }
    
    else
    {
        feedURL = [NSURL URLWithString:@"https://graph.facebook.com/me/feed"];
    }

    
    SLRequest *feedRequest = [SLRequest
                              requestForServiceType:SLServiceTypeFacebook
                              requestMethod:SLRequestMethodPOST
                              URL:feedURL
                              parameters:parameters];
    
    if(self.attachmentImage)
    {
        NSData *imageData = UIImagePNGRepresentation(self.attachmentImage);
        [feedRequest addMultipartData:imageData withName:@"source" type:@"multipart/form-data" filename:@"Image"];
    }
    
    feedRequest.account = self.facebookAccount;
    
    [feedRequest performRequestWithHandler:^(NSData *responseData,
                                             NSHTTPURLResponse *urlResponse, NSError *error)
     {
         
         NSLog(@"Facebook post statusCode: %u", [urlResponse statusCode]);
         
         if([urlResponse statusCode] == 200)
         {
             [self performSelectorOnMainThread:@selector(reportSuccessOrError:) withObject:@"Your message has been posted to Facebook" waitUntilDone:NO];

         }
         
         else if(error != nil)
         {
             [self performSelectorOnMainThread:@selector(faceBookError:) withObject:error waitUntilDone:NO];
         }
         
     }];
}

-(void)facebookTimeline
{
    NSURL *feedURL = [NSURL URLWithString:@"https://graph.facebook.com/me/feed"];
    
    SLRequest *feedRequest = [SLRequest
                              requestForServiceType:SLServiceTypeFacebook
                              requestMethod:SLRequestMethodGET
                              URL:feedURL
                              parameters:nil];
    
    feedRequest.account = self.facebookAccount;
    
    [feedRequest performRequestWithHandler:^(NSData *responseData,
                                             NSHTTPURLResponse *urlResponse, NSError *error)
     {
         
         NSLog(@"Facebook post statusCode: %u", [urlResponse statusCode]);
         
         if([urlResponse statusCode] == 200)
         {
             
             NSLog(@"%@", [[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error] objectForKey:@"data"]);
             [self performSelectorOnMainThread:@selector(presentTimeline:) withObject:[[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error] objectForKey:@"data"] waitUntilDone:NO];
         }
         
         else if(error != nil)
         {
             [self performSelectorOnMainThread:@selector(faceBookError:) withObject:error waitUntilDone:NO];
             
         }
         
     }];
}

- (IBAction)twitterAction:(id)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Twitter Actions" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Composer", @"Auto-Post", @"Timeline", nil];
    actionSheet.tag = kActionSheetTwitter;
    [actionSheet showInView: self.view];
    [actionSheet release];
    
}

-(void)twitterComposer
{
    if([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
    {
        
        SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
        
        SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){
            if (result == SLComposeViewControllerResultCancelled)
            {
                NSLog(@"Cancelled");
            }
            
            else
            {
                NSLog(@"Done");
            }
            
            [controller dismissViewControllerAnimated:YES completion:nil];
            [socialTextView becomeFirstResponder];

        };
        
        controller.completionHandler = myBlock;
        
        [controller setInitialText:@"Check out my app:"];
        [controller addImage:[UIImage imageNamed:@"Kitten.jpg"]];
        [controller addURL:[NSURL URLWithString:@"http://amzn.to/Um85L0"]];
        
        [controller removeAllImages];
        [controller removeAllURLs];
        
        [self presentViewController:controller animated:YES completion:nil];
        
    }
    
    else
    {
        NSLog(@"Twitter Composer is not available.");
    }
}

-(void)twitterPost
{
    ACAccountStore *account = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier: ACAccountTypeIdentifierTwitter];
        
        
    [account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error)
    {
        if(error != nil)
        {
            [self performSelectorOnMainThread:@selector(reportSuccessOrError:) withObject:[error localizedDescription] waitUntilDone:NO];

        }
        
        if (granted == YES)
        {
            NSArray *arrayOfAccounts = [account
                                        accountsWithAccountType:accountType];
            
            if ([arrayOfAccounts count] > 0)
            {
                ACAccount *twitterAccount = [arrayOfAccounts lastObject];
        
                
                NSURL *requestURL = nil;
                
                if(self.attachmentImage)
                {
                    requestURL = [NSURL URLWithString:@"https://upload.twitter.com/1/statuses/update_with_media.json"];
                }
                
                else
                {
                    requestURL = [NSURL URLWithString:@"http://api.twitter.com/1/statuses/update.json"];
                }
                
                SLRequest *postRequest = [SLRequest
                                          requestForServiceType:SLServiceTypeTwitter
                                          requestMethod:SLRequestMethodPOST
                                          URL:requestURL parameters:nil];
                
                if(socialTextView.text)
                {
                   [postRequest addMultipartData:[@"A Tweet Text!" dataUsingEncoding:NSUTF8StringEncoding] withName:@"status" type:@"multipart/form-data" filename:nil];
                }
                
                if(self.attachmentImage)
                {
                    NSData *imageData = UIImageJPEGRepresentation(self.attachmentImage, 1.0);
                    [postRequest addMultipartData:imageData withName:@"media" type:@"image/jpg" filename:@"Image.jpg"];
                }
                
                postRequest.account = twitterAccount;
                
                [postRequest performRequestWithHandler:^(NSData *responseData,
                                                         NSHTTPURLResponse *urlResponse, NSError *error){
                    if(error != nil)
                    {
                        [self performSelectorOnMainThread:@selector(reportSuccessOrError:) withObject:[error localizedDescription] waitUntilDone:NO];
                    }

                    if([urlResponse statusCode] == 200)
                    {
                        [self performSelectorOnMainThread:@selector(reportSuccessOrError:) withObject:@"Your message has been posted to Twitter" waitUntilDone:NO];
                    }

                }];
                
            }
        }
        
        else
        {
             NSLog(@"Access Denied");
        }
    }];
}

-(void)twitterTimeline
{
    ACAccountStore *account = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier: ACAccountTypeIdentifierTwitter];
    
    [account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error)
     {
         if(error != nil)
         {
             [self performSelectorOnMainThread:@selector(reportSuccessOrError:) withObject:[error localizedDescription] waitUntilDone:NO];
         }
         
         if (granted == YES)
         {
             NSArray *arrayOfAccounts = [account
                                         accountsWithAccountType:accountType];
             
             if ([arrayOfAccounts count] > 0)
             {
                 ACAccount *twitterAccount = [arrayOfAccounts lastObject];
                 NSURL *requestURL = [NSURL URLWithString:@"http://api.twitter.com/1/statuses/home_timeline.json"];
                 
                 NSDictionary *options = @{
                 @"count" : @"20",
                 @"include_entities" : @"1"};
                 
                 SLRequest *postRequest = [SLRequest
                                           requestForServiceType:SLServiceTypeTwitter
                                           requestMethod:SLRequestMethodGET
                                           URL:requestURL parameters:options];
                 
                 postRequest.account = twitterAccount;
                 
                 [postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
                  {
                      if(error != nil)
                      {
                          [self reportSuccessOrError: [error localizedDescription]];
                          
                      }
                      
                      [self performSelectorOnMainThread:@selector(presentTimeline:) withObject:[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error] waitUntilDone:NO];
                      
                  }];
             }
         }
     }];
}

-(void)presentTimeline:(NSArray *)timelineArray;
{
    
    ICFTimelineViewController *timelineVC = [[ICFTimelineViewController alloc] init];
    timelineVC.timelineData = timelineArray;
    [self presentViewController:timelineVC animated:YES completion:nil];
    [timelineVC release];

}

- (IBAction)attachImage:(id)sender
{
    self.attachmentImage = nil;
    
    picker = [[UIImagePickerController alloc] init];
    
    picker.delegate = self;
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        
    {
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        
    } else
        
    {
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
    }
    
    
    [self presentViewController:picker
                       animated:YES
                     completion:^(){
                         
                     }];
}
    

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)VC
{
    [VC dismissViewControllerAnimated:YES completion:^(){
    
        [picker release];

    }];
}


- (void)imagePickerController:(UIImagePickerController *)VC didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    self.attachmentImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    [VC dismissViewControllerAnimated:YES completion:^(){
    
        [picker release];

    }];
}

-(void)reportSuccessOrError:(NSString *)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
    [alert show];
    [alert release];
    
    socialTextView.text = nil;
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    int characterCount = [[textView text] length];
    
    characterCount -= range.length;
    characterCount += text.length;
    
    if(characterCount <= 140)
    {
        charCountLabel.text = [NSString stringWithFormat:@"%u Characters Remaining", (140-characterCount)];
        return YES;
    }
    
    return NO;
}

- (void)dealloc
{
    [socialTextView release];
    [charCountLabel release];
    [super dealloc];
}
@end
