//
//  AuthenticationView.m
//  Project
//
//  Created by Phan Quang Hoang on 8/26/13.
//  Copyright (c) 2013 Phan Quang Hoang. All rights reserved.
//

#import "AuthenticationView.h"
#import "TopScreenView.h"
#import "ResearchListView.h"
#import "ListItemChange.h"
#import "AppDelegate.h"
#import "JSONKit.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "ConnectionManager.h"

static inline int sizeHeight() {
    return [UIScreen mainScreen].bounds.size.height;
}
@interface AuthenticationView ()

@end

@implementation AuthenticationView
{
    UITextField *aTextField;
//    UIView *indicatorView;
    
    BOOL isAlert;
    int errorCode;
    NSString *errorText;
    NSCharacterSet *blockedCharacters;
    
    CGRect inputCodeFrame;
}
@synthesize errorLabel = _errorLabel;
@synthesize requestInputCode;
@synthesize txfInputCode;
@synthesize mailNotSendLabel;
@synthesize activityView;

/*
 ⁃	Dealloc
 ⁃	Initialization
 ⁃	View lifecycle
 ⁃	Data loading
 ⁃	Private methods
 ⁃	Button selectors
 ⁃	Delegates
 */

#pragma mark - Dealloc
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Initialization
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        blockedCharacters = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
        
    }
    return self;
}

/* Layout */
- (void)initView
{
    requestInputCode.numberOfLines = 0;
    CGRect currentFrame = requestInputCode.frame;
    CGSize max = CGSizeMake(288, FLT_MAX);
    CGSize expected = [requestInputCode.text sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:max lineBreakMode:NSLineBreakByWordWrapping];
    currentFrame.size.height = expected.height;
    requestInputCode.frame = currentFrame;
    
    mailNotSendLabel.numberOfLines = 0;
    CGRect mailNotSendFrame = mailNotSendLabel.frame;
    CGSize size = [mailNotSendLabel.text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:max lineBreakMode:NSLineBreakByWordWrapping];
    mailNotSendFrame.size.height = size.height;
    mailNotSendLabel.frame = mailNotSendFrame;
}

#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self initView];
    isAlert = NO;
    
    UIButton *leftButton = [[UIButton alloc] init];
    [leftButton setBackgroundImage:gImageHeaderModify forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backView) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setFrame:CGRectMake(280, 25, 49, 31)];
    
    UIBarButtonItem *leftButtonItem;
    if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
        [leftButton setFrame:CGRectMake(0, 0, 49, 31)];
        UIView *backButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 49, 31)];
        backButtonView.bounds = CGRectOffset(backButtonView.bounds, 10, 0);
        [backButtonView addSubview:leftButton];
        leftButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButtonView];
    }
    else{
        leftButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    }
    self.navigationItem.leftBarButtonItem = leftButtonItem;
    
    
    
    tapOnView = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapAnywhere:)];
    
    CGRect rect = mainScroll.frame;
    rect.size.height = SIZE_HEIGHT - 44 - 20;
    mainScroll.contentSize = CGSizeMake(320.0f, mainView.frame.size.height + 20);
    mainScroll.frame = rect;
    [mainScroll addSubview:mainView];
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:gImageBackground];

    // ActivityIndicator
    activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityView.color = [UIColor grayColor];
    CGRect frame = activityView.frame;
    frame.origin.x = self.view.frame.size.width / 2 - frame.size.width / 2;
    frame.origin.y = SIZE_HEIGHT / 2 - frame.size.height / 2;
    activityView.frame = frame;
    activityView.hidesWhenStopped = YES;
    [activityView stopAnimating];
    [self.tabBarController.view addSubview:activityView];
//    // init view
//    indicatorView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, SIZE_HEIGHT - 20)];
//    indicatorView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.0];
    
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:@"YES" forKey:NSUserDefaultRegisting];
    [ud synchronize];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    screenRect.origin.y = 20;
    screenRect.size.height = SIZE_HEIGHT + 52 - 20;
    self.tabBarController.view.frame = screenRect;
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
    
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    screenRect.origin.y = 20;
    screenRect.size.height = SIZE_HEIGHT + 52 - 20;
    self.tabBarController.view.frame = screenRect;
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    
}

#pragma mark - Data loading
/* auth code api */
- (void)applyAuthorCodeConfirm
{
//    [self.tabBarController.view addSubview:indicatorView];
//    [self.tabBarController.view addSubview:activityView];
    [activityView startAnimating];
    
    
    NSString *urlAsString = CheckAuthCodeAPI;
    NSURL *url = [NSURL URLWithString:urlAsString];
    
    NSString *hostid = [[NSUserDefaults standardUserDefaults] objectForKey:NSUserDefaultHostid];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setTimeOutSeconds:5.0];
    [request addPostValue:[self appDelegate].keyId forKey:@"keyid"];
    [request addPostValue:hostid forKey:@"hostid"];
    [request addPostValue:self.txfInputCode.text forKey:@"authcode"];
    [request setDelegate:self];
    [request startAsynchronous];
}

#pragma mark - Private methods
/* app delegate */
- (AppDelegate *)appDelegate
{
    return  (AppDelegate *)[UIApplication sharedApplication].delegate;
}

#pragma mark -
/* hide keyboard */
- (void)didTapAnywhere:(UITapGestureRecognizer*)recognizer
{
    [self.txfInputCode resignFirstResponder];
    [self.view removeGestureRecognizer: tapOnView];
}

#pragma mark - 
/* validate input */
- (NSString *)validate
{
    NSString *input_code = self.txfInputCode.text;
    NSString *error = nil;
    if ([input_code isEqualToString:@""] == YES) {
        error = INPUT_EMPTY;
    }
    return error;
}

/* Result OK */
- (void)validateAuthorConfirm
{
    //New Spec
    AppDelegate *appDelegate = [self appDelegate];
    [appDelegate.tabBarController setSelectedIndex:1];
    UINavigationController *navigationConttoller = [appDelegate.tabBarController.viewControllers objectAtIndex:0];
    //TopScreenView *viewCtr = (TopScreenView *)[navigationConttoller.viewControllers objectAtIndex:0];
    [navigationConttoller popToRootViewControllerAnimated:YES];
    
    //    TopScreenView *topScreen = [[TopScreenView alloc] initWithNibName:@"TopScreenView" bundle:[NSBundle mainBundle]];
    //    [self.navigationController pushViewController:topScreen animated:YES];
    //    self.navigationController.viewControllers = [[NSArray alloc] initWithObjects:topScreen, nil];
}

#pragma mark -
/* alert message */
//- (void)alertError:(NSString *)stringError
//{
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
//                                                    message:stringError
//                                                   delegate:self
//                                          cancelButtonTitle:CANCEL_BUTTON_2
//                                          otherButtonTitles:nil];
//    [alert show];
//    isAlert = YES;
//}

#pragma mark - Button selectors
/* Modify button */
- (IBAction)modifyInput:(id)sender
{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:@"NO" forKey:NSUserDefaultRegisting];
    [ud synchronize];
    //[[NSNotificationCenter defaultCenter] postNotificationName:@"backRegis" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

/* Regist */
- (IBAction)regisAuthentication:(id)sender
{
    if([self validate] == nil) {
        [self applyAuthorCodeConfirm];  
    }
    else {
        [UIView beginAnimations:@"error" context:nil];
        [UIView setAnimationDuration:0.3];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
        
        NSString *error = [self validate];
        CGSize theSize = [error sizeWithFont:[UIFont systemFontOfSize:15.0f] constrainedToSize:CGSizeMake(300, FLT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
        CGRect rect = _errorLabel.frame;
        rect.size.height = theSize.height;
        _errorLabel.frame = rect;
        _errorLabel.hidden = NO;
        _errorLabel.text = error;
        
        rect = mainView.frame;
        rect.origin.y = _errorLabel.frame.size.height + _errorLabel.frame.origin.y;
        mainView.frame = rect;
        
        mainScroll.contentOffset = CGPointMake(0, 0);
        mainScroll.contentSize = CGSizeMake(320.0f, _errorLabel.frame.size.height + _errorLabel.frame.origin.y + mainView.frame.size.height);
        
        [UIView commitAnimations];
    }
    
}

/* Back view */
- (void)backView
{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:@"NO" forKey:NSUserDefaultRegisting];
    [ud synchronize];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    aTextField = textField;
    [textField resignFirstResponder];
    [self.view removeGestureRecognizer: tapOnView];
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    //aTextField = textField;
    [self.view addGestureRecognizer:tapOnView];
}

- (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
{
    if (range.location == 6) {
        return NO;
    }
    NSCharacterSet *unacceptedInput = nil;
    unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:NUMERIC] invertedSet];
    return ([[characters componentsSeparatedByCharactersInSet:unacceptedInput] count] <= 1);
}

#pragma mark- ASIHTTPRequestDelegate
/* request finish */
- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSData *responseData = [request responseData];
    NSDictionary *resultsArray = [responseData objectFromJSONData];
//    NSLog(@"JSON %@", resultsArray);
    
    NSArray *keyResult = [resultsArray allKeys];
    if ([[keyResult objectAtIndex:0] isEqualToString:@"error"]) {
        NSDictionary *error = [resultsArray objectForKey:[keyResult objectAtIndex:0]];
        errorCode = [[error objectForKey:@"code"] integerValue];
        
        [activityView stopAnimating];
//        [indicatorView removeFromSuperview];
        
        [UIView beginAnimations:@"error" context:nil];
        [UIView setAnimationDuration:0.3];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
        
        NSString *errorString = ERROR;
        CGSize theSize = [errorString sizeWithFont:[UIFont systemFontOfSize:15.0f] constrainedToSize:CGSizeMake(300, FLT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
        CGRect rect = _errorLabel.frame;
        rect.size.height = theSize.height;
        _errorLabel.frame = rect;
        _errorLabel.hidden = NO;
        _errorLabel.text = errorString;
        
        rect = mainView.frame;
        rect.origin.y = _errorLabel.frame.size.height + _errorLabel.frame.origin.y;
        mainView.frame = rect;
        
        mainScroll.contentOffset = CGPointMake(0, 0);
        mainScroll.contentSize = CGSizeMake(320.0f, _errorLabel.frame.size.height + _errorLabel.frame.origin.y + mainView.frame.size.height);
        
        [UIView commitAnimations];
    } else {
        NSString *resultTemp = [resultsArray objectForKey:@"result"];
        int result = [resultTemp intValue];
        if (result == 1) {
            
            //success
            NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
            [ud setObject:@"NO" forKey:NSUserDefaultRegisting];
            [ud setObject:[ud objectForKey:@"mailAddressRegister"] forKey:NSUserDefaultMailAddress];
            [ud setObject:[ud objectForKey:@"passWordRegister"] forKey:NSUserDefaultPassWord];
            [ud synchronize];
            
            [self appDelegate].hostId = [ud objectForKey:NSUserDefaultHostid];
            
            [self appDelegate].answercountButon.hidden = YES;
            [[self appDelegate].answercountButon setTitle:[NSString stringWithFormat:@"%d", 0] forState:UIControlStateNormal];
            
            [self appDelegate].readcountButon.hidden = YES;
            [[self appDelegate].readcountButon setTitle:[NSString stringWithFormat:@"%d", 0] forState:UIControlStateNormal];
            
            [self validateAuthorConfirm];
//            [activityView removeFromSuperview];
            [activityView stopAnimating];
//            [indicatorView removeFromSuperview];
        }
    }
}

/* request fail */
- (void)requestFailed:(ASIHTTPRequest *)request
{
    //NSError *error = [request error];
//    [activityView removeFromSuperview];
    [activityView stopAnimating];
//    [indicatorView removeFromSuperview];
//    if (!isAlert) {
//        [self alertError:ALERT_MESSAGE];
//    }
}

#pragma mark - AlertViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    ConnectionManager *connectManager = [[ConnectionManager alloc] init];
    if (buttonIndex == 0) {
        if (![connectManager isConnectNetwork]) {
            //[self alertError:ALERT_MESSAGE];
        } else {
            isAlert = NO;
            [self applyAuthorCodeConfirm];
        }
    }
}
@end
