//
//  RTTViewController.m
//  NG911
//
//  Created by Mason Silber on 11/28/11.
//  Copyright (c) 2011 Columbia University. All rights reserved.
//

#import "RTTViewController.h"
#import <QuartzCore/QuartzCore.h>

#define KEYBOARD_HEIGHT 216
#define kLostDomainKey  @"lostdomain"

@implementation RTTViewController
@synthesize callTakerTextView,userTextView;

-(void)dealloc
{
    [callTakerTextView release];
    [userTextView release];
    [pjclient destroy];
    [locationManager release];
    [userTextLabel release];
    
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        [[self view] setBackgroundColor:[UIColor underPageBackgroundColor]];
        
        UIBarButtonItem *hideKeyboard = [[UIBarButtonItem alloc] initWithTitle:@"Hide Keyboard" style:UIBarButtonItemStyleBordered target:self action:@selector(hideKeyboard)];
        [hideKeyboard setEnabled:NO];
        [[self navigationItem] setRightBarButtonItem:hideKeyboard];
        [hideKeyboard release];

        UIBarButtonItem *quickResponse = [[UIBarButtonItem alloc] initWithTitle:@"Quick Response" style:UIBarButtonItemStyleBordered target:self action:@selector(createQuickResponse:)];
        [[self navigationItem] setLeftBarButtonItem:quickResponse];
        [quickResponse release];
        
        UILabel *responderLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 20)];
        [responderLabel setText:@"Responder:"];
        [responderLabel setBackgroundColor:[UIColor clearColor]];
        [[self view] addSubview:responderLabel];
        [responderLabel release];
        
        
        callTakerTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 20, [[self view] frame].size.width, ([[self view] frame].size.height-44)/2 -20)];
        [callTakerTextView setEditable:NO];
        [callTakerTextView setUserInteractionEnabled:YES];
        [callTakerTextView setDelegate:self];
        [[callTakerTextView layer] setBorderColor:[[UIColor colorWithRed:10/255.0f green:73/255.0f blue:161/255.0f alpha:1.0] CGColor]];
        [[callTakerTextView layer] setBorderWidth:3.0];
        [callTakerTextView setFont:[UIFont systemFontOfSize:[(AppDelegate *)[[UIApplication sharedApplication] delegate] textSize]]];
        [callTakerTextView setBackgroundColor:[UIColor whiteColor]];
        
        userTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, [callTakerTextView frame].size.height + 20, [[self view] frame].size.width, ([[self view] frame].size.height-44)/2)];
        [userTextView setDelegate:self];
        [[userTextView layer] setBorderColor:[[UIColor colorWithRed:4/255.0f green:110/255.0f blue:13/255.0f alpha:1.0] CGColor]];
        [[userTextView layer] setBorderWidth:3.0];
        [userTextView setFont:[UIFont systemFontOfSize:[(AppDelegate *)[[UIApplication sharedApplication] delegate] textSize]]];
        [userTextView setAutocorrectionType:UITextAutocorrectionTypeNo];
        [userTextView setAutocapitalizationType:UITextAutocapitalizationTypeNone];
        
        //Examining to remove some functionality
//        NSArray *gestures = [userTextView gestureRecognizers];

        
        userTextLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, ([userTextView frame].size.height - 20)/2, [[self view] frame].size.width, 20)];
        [userTextLabel setText:@"Tap to type"];
        [userTextLabel setHidden:NO];
        [userTextLabel setTextColor:[UIColor lightGrayColor]];
        [userTextLabel setTextAlignment:UITextAlignmentCenter];
        [userTextView addSubview:userTextLabel];

        maxTextViewSize = CGSizeMake([[self view] frame].size.width, 1000);
        currentTextViewSize = [userTextView frame].size;
        
        [[self view] addSubview:callTakerTextView];
        [[self view] addSubview:userTextView];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
   
    
    // init location stuff
    locationManager = [[CLLocationManager alloc] init];
    [locationManager setDelegate:self];
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    [locationManager startUpdatingLocation];
    numberOfTimesLocationUpdated = 0;
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

/*-(void)textViewDidChange:(UITextView *)textView
{    
    if([textView hasText])
    {
        if([textView textColor] == [UIColor lightGrayColor])
        {
            [textView setTextColor:[UIColor blackColor]];
        }
        
        CGSize textViewSize = [[textView text] sizeWithFont:[textView font] constrainedToSize:maxTextViewSize lineBreakMode:UILineBreakModeWordWrap];
        if(textViewSize.height < ([[self view] frame].size.height-44)/2)
        {
            textViewSize.height = ([[self view] frame].size.height-44)/2;
        }
        
        if(textViewSize.height != currentTextViewSize.height)
        {
            currentTextViewSize = textViewSize;
            if(textView == callTakerTextView)
            {
                [callTakerTextView setContentSize:CGSizeMake(textViewSize.width, textViewSize.height)];
                [callTakerTextView setContentOffset:CGPointMake([callTakerTextView contentOffset].x, [callTakerTextView contentSize].height-[callTakerTextView frame].size.height)];
            }
            else
            {
                [userTextView setContentSize:CGSizeMake(textViewSize.width, textViewSize.height)];
                [userTextView setContentOffset:CGPointMake([userTextView contentOffset].x, [userTextView contentSize].height-[userTextView frame].size.height)];
            }
        }
    }
}*/

-(void)textViewDidBeginEditing:(UITextView *)textView
{
    [userTextLabel setHidden:YES];
    
    [UIView animateWithDuration:0.25 animations:^
     {

         [callTakerTextView setFrame:CGRectMake(0, 20, [[self view] frame].size.width, ([[self view] frame].size.height-KEYBOARD_HEIGHT)/2-20)];
       
         [textView setFrame:CGRectMake(0, ([[self view] frame].size.height-KEYBOARD_HEIGHT)/2, [[self view] frame].size.width, ([[self view] frame].size.height - KEYBOARD_HEIGHT)/2)];
     }];
    
    if(textView == userTextView && [[textView text] isEqualToString:@"Tap here to send message"])
    {
        [textView setText:@""];
        [textView setTextColor:[UIColor blackColor]];
    }
    [[[self navigationItem] rightBarButtonItem] setEnabled:YES];
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    [UIView animateWithDuration:0.25 animations:^
     {
         [callTakerTextView setFrame:CGRectMake(0, 20, [[self view] frame].size.width, [[self view] frame].size.height/2 - 20)];
         
         [userTextView setFrame:CGRectMake(0, [callTakerTextView frame].size.height + 20, [[self view] frame].size.width, [[self view] frame].size.height/2)];
     }];
    
    if(![userTextView hasText])
    {
        [userTextLabel setHidden:NO];
    }
    
    [[[self navigationItem] rightBarButtonItem] setEnabled:NO];
}

-(void)textViewDidChange:(UITextView *)textView
{
    if(textView == callTakerTextView)
    {
        [callTakerTextView setContentOffset:CGPointMake(callTakerTextView.contentOffset.x,callTakerTextView.contentSize.height - callTakerTextView.frame.size.height) animated:YES];
    }
}

-(void)hideKeyboard
{
    if([callTakerTextView isFirstResponder])
    {
        [callTakerTextView resignFirstResponder];
    }
    else if([userTextView isFirstResponder])
    {
        [userTextView resignFirstResponder];
    }
    
    [UIView animateWithDuration:0.25 animations:^
     {
         [callTakerTextView setFrame:CGRectMake(0, 20, [[self view] frame].size.width, [[self view] frame].size.height/2 - 20)];
         
         [userTextView setFrame:CGRectMake(0, [callTakerTextView frame].size.height + 20, [[self view] frame].size.width, [[self view] frame].size.height/2)];
     }];
    
    if(![userTextView hasText])
    {
        [userTextLabel setHidden:NO];
    }
    
    [[[self navigationItem] rightBarButtonItem] setEnabled:NO];
}

-(void)createQuickResponse:(id)sender
{
    QuickResponseViewController *quickResponse = [[QuickResponseViewController alloc] initWithNibName:nil bundle:nil];
    [quickResponse setMyDelegate:self];
    [quickResponse setTitle:@"Quick Response"];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:quickResponse];
    [self presentModalViewController:nav animated:YES];
    [quickResponse release];
    [nav release];
}

//QuickResponseDelegate method
-(void)quickResponseDismissed:(NSString *)typeOfResponse
{
    
    //Need to create special messages here
    if ([typeOfResponse isEqualToString:@"Cancel"]) 
    {
        return;
    }
    else
    {
        [userTextView setText:[NSString stringWithFormat:@"Quick response:%@",typeOfResponse]];
        
        if(![userTextLabel isHidden])
        {
            [userTextLabel setHidden:YES];
        }
    }
}

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    currentLocationCoordinates = newLocation.coordinate;
    // NSLog(@"%f,%f",currentLocationCoordinates.latitude, currentLocationCoordinates.longitude);
    
    // Use LoST to get closes SIP server
    if (oldLocation == nil){
        [self performSelectorInBackground:@selector(initLostRequest) withObject:nil];    
    }
    
    //Removed this line because it continually updates, making the location more accurate
    //We also need this for the PIDF client, so I prefer to let it update.
    
    //    [locationManager stopUpdatingLocation]; // only need it once when launching
    
    if(numberOfTimesLocationUpdated < 3)
    {
        numberOfTimesLocationUpdated++;
    }
    else
    {
        //        [self performSelectorInBackground:@selector(initLostRequest) withObject:nil];    
        [locationManager stopUpdatingLocation];
        [locationManager startMonitoringSignificantLocationChanges];
    }
}


-(void) didFinishLoadingWithStatus:(int)status {
    if (status == 0) {
        printf("PJClient loaded successfully with status: %d\n", status);
    }
}

-(void) realtimeMessageReceivedwithContent:(NSString *)content {
    // get the string and append it to textbox
    
    callTakerTextView.text = [callTakerTextView.text stringByAppendingString:content];    
}

-(void) realtimeBackspaceReceived {
   
    NSUInteger length = [callTakerTextView.text length];
    
    if (length > 0) {
        callTakerTextView.text = [callTakerTextView.text substringToIndex:(length - 1)];
    }
    
}

-(void) realtimeReturnReceived {
    
    callTakerTextView.text = [callTakerTextView.text stringByAppendingFormat:@"\n"];
    
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    const char * c;
    
    if(range.length == 1 ) {
        // backspace pressed
        char bs = '\b';
        c = &bs;
    } else {
        c = [text UTF8String];
    }
    
    [pjclient charTyped:c];
    
    return YES;

}


-(void) initLostRequest 
{

    LostClient *client = [[LostClient alloc] init];
    
    NSLog(@"Lat: %f, Long: %f", currentLocationCoordinates.latitude, currentLocationCoordinates.longitude);
    
    psap_uri = [client lostRequestWithLatitude:currentLocationCoordinates.latitude longitude:currentLocationCoordinates.longitude];
    
    // set the sip domain URI
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:psap_uri forKey:kLostDomainKey];
    
    // start the pjsip client
    
    pjclient = [PJClient sharedPJClient]; // singleton
    pjclient.delegate = self;
    
    
    NSOperationQueue *queue = [NSOperationQueue new];
    
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:pjclient selector:@selector(initClientWithLocation:) object:locationManager.location];
    
    [queue addOperation:operation];
    
//    NSInvocationOperation *operation2 = [[NSInvocationOperation alloc] initWithTarget:pjclient selector:@selector(initMedia) object:nil];
    
    
    // [queue addOperation:operation2];
    [operation release];
//    [operation2 release];
    
    [queue release];
    [client release];
    
}




@end
