//
//  BaseViewController.m
//  TaiZhouTobacco_assets
//
//  Created by JianjiYuan on 14-5-15.
//  Copyright (c) 2014年 JianjiYuan. All rights reserved.
//

#import "BaseViewController.h"
#import <RDVTabBarController.h>

@interface BaseViewController () < UITextFieldDelegate, UITextViewDelegate >
{
@private
    BOOL _hasFoundTextView;
    BOOL _viewDidAppeared;
    BOOL _keyboardWillHidden;
    CGFloat _keyboradHeight;
    
    UITextField *_tempTextField;
    UITextView *_tempTextView;
}

@end

@implementation BaseViewController

#pragma mark =============  Memery Release  =============

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self disposeProperties];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if ([self isViewLoaded] && self.view.window == nil) {
        [self disposeProperties];
    }
}

- (void)disposeProperties
{
    self.networkMgr = nil;
    _tempTextView = nil;
    _tempTextField = nil;
}

#pragma mark =============  Initiation Method  =============

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
            self.edgesForExtendedLayout = UIRectEdgeNone;
            self.extendedLayoutIncludesOpaqueBars = NO;
            self.modalPresentationCapturesStatusBarAppearance = NO;
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        
    }
    return self;
}

#pragma mark =============  Life Circle  =============

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBarHidden = NO;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnBack setBackgroundImage:[UIImage imageNamed:@"NavBar/btn_nav_back.png"] forState:UIControlStateNormal];
    [btnBack sizeToFit];
    [btnBack addTarget:self action:@selector(btnBackClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController navbarLeftItemCustomized:@[btnBack] onwer:self.navigationItem];
    
    UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [[self view] addGestureRecognizer:recognizer];
    
    recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
    [[self view] addGestureRecognizer:recognizer];
    
    recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionUp)];
    [[self view] addGestureRecognizer:recognizer];
    
    recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionDown)];
    [[self view] addGestureRecognizer:recognizer];
    
}

-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer{
    
    if(recognizer.direction==UISwipeGestureRecognizerDirectionDown) {
        
        NSLog(@"swipe down");
        //执行程序
    }
    if(recognizer.direction==UISwipeGestureRecognizerDirectionUp) {
        
        NSLog(@"swipe up");
        //执行程序
    }
    
    if(recognizer.direction==UISwipeGestureRecognizerDirectionLeft) {
        
        NSLog(@"swipe left");
        //执行程序
    }
    
    if(recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
        
        NSLog(@"swipe right");
        //执行程序
    }
    
}

- (void)setViewLayoutConstraint
{

}

- (void)registObserverOfTextInputView
{
     _hasFoundTextView = NO;
    
    if ([self findTextViewsInView:self.view]) {
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resignKeyboard) name:kNotificationEndEdit object:nil];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    _viewDidAppeared = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    _viewDidAppeared = NO;
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)btnBackClick:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)findTextViewsInView:(UIView *)view
{
    for (UIView *subView in view.subviews) {
        
        if (subView.subviews.count > 0) {
            [self findTextViewsInView:subView];
        }
        if ([subView isKindOfClass:[UITextField class]] ||
            [subView isKindOfClass:[UITextView class]]) {
            
            if ([subView isKindOfClass:[UITextField class]]) {
                
                ((UITextField *)subView).delegate = self;
                _hasFoundTextView = YES;
            }
            if ([subView isKindOfClass:[UITextView class]]) {
                ((UITextView *)subView).delegate = self;
                _hasFoundTextView = YES;
            }
        }
        
    }
    return _hasFoundTextView;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (_hasFoundTextView && _viewDidAppeared) {
        [self resignKeyboard];
    }
    
}



- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if (!(_hasFoundTextView && _viewDidAppeared)) {
        return;
    }
    _tempTextView = textView;
    _tempTextField = nil;
    _keyboardWillHidden = NO;
    [self tranformViewWith:_tempTextView];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (!(_hasFoundTextView && _viewDidAppeared)) {
        return;
    }
    _tempTextField = textField;
    _tempTextView = nil;
    _keyboardWillHidden = NO;
    [self tranformViewWith:_tempTextField];
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    _keyboardWillHidden = YES;
    self.view.transform = CGAffineTransformIdentity;
}

- (void)keyboardDidChangeFrame:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [aValue CGRectValue].size;
    UIDeviceOrientation deviceOrientation = [[UIDevice currentDevice] orientation];
    if (UIDeviceOrientationIsLandscape(deviceOrientation)) {
        _keyboradHeight = keyboardSize.width;
    } else {
        _keyboradHeight = keyboardSize.height;
    }

    if (!_keyboardWillHidden) {
        [self tranformViewWith:_tempTextField];
        [self tranformViewWith:_tempTextView];
    }

}
- (void)resignKeyboard
{
    [self.view endEditing:YES];
    self.view.transform = CGAffineTransformIdentity;
}

- (void)tranformViewWith:(UIView *)firstResponseView
{
    if (!firstResponseView) {
        return;
    }
    CGFloat startCenterY;
    
    if (firstResponseView.superview != self.view) {
        CGRect rectToSuper = [firstResponseView.superview convertRect:firstResponseView.frame toView:self.view];
        startCenterY = CGRectGetMidY(rectToSuper);
        
    }else {
        startCenterY = CGRectGetMidY(firstResponseView.frame);
    }
    
    CGFloat endCenterY = (CGRectGetHeight(self.view.bounds) - _keyboradHeight)/2;
    
    if (endCenterY >= startCenterY) {
        return;
    }
    CGFloat transformHeight = startCenterY-endCenterY;
    if (transformHeight > _keyboradHeight) {
        transformHeight = _keyboradHeight;
    }
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.view.transform = CGAffineTransformMakeTranslation(0, -transformHeight);
    }];
}

#pragma mark =============  Properties Lazy Load  =============

- (BRNetworkMgr *)networkMgr
{
    if (!_networkMgr) {
        self.networkMgr = [BRNetworkMgr getInstance];
        _networkMgr.delegate = self;
    }
    return _networkMgr;
}

@end
