//
//  ICRLoginViewController.m
//  XFFruit
//
//  Created by Xummer on 3/22/15.
//  Copyright (c) 2015 Xummer. All rights reserved.
//

#import "ICRLoginViewController.h"
#import "ICRLoginContentView.h"

#import "GXFFunctionDB.h"
#import "GXFFunctionDBHelper.h"

#define LOGIN_CONTAINER_LEFT_MARGIN         (20)
#define LOGIN_CONTAINER_HEIGHT              (450)

@interface ICRLoginViewController ()
{
    CGFloat m_fDefaultContainerY;
}
@property (strong, nonatomic) ICRLoginContentView *m_containerView;
@end

@implementation ICRLoginViewController

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupSubviews];
}

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

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    if (m_fDefaultContainerY == 0) {
        m_fDefaultContainerY = _m_containerView.y;
    }
}

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

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
    [notiCenter addObserver:self
                   selector:@selector(inputTextEditChanged:)
                       name:UITextFieldTextDidChangeNotification
                     object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
    [notiCenter removeObserver:self];
}

#pragma mark - Private Method
- (void)setupSubviews {
    UIImageView *bg = [[UIImageView alloc] initWithFrame:self.view.bounds];
    bg.image = [UIImage imageNamed:@"LoginBG"];
    [bg autoresizingWithStrechFullSize];
    
    UITapGestureRecognizer *tapGesture =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(onBGTapped:)];
    bg.userInteractionEnabled = YES;
    [bg addGestureRecognizer:tapGesture];
    
    [self.view addSubview:bg];
    
    self.m_containerView =
    [[ICRLoginContentView alloc] initWithFrame:(CGRect){
        .origin.x = LOGIN_CONTAINER_LEFT_MARGIN,
        .origin.y = (self.view.height - LOGIN_CONTAINER_HEIGHT) * .5f,
        .size.width = self.view.width - 2 * LOGIN_CONTAINER_LEFT_MARGIN,
        .size.height = LOGIN_CONTAINER_HEIGHT
    }
                                     showCCode:YES];
    [_m_containerView autoresizingWithVerticalCenter];
    
    [_m_containerView.m_loginBtn addTarget:self
                                    action:@selector(onLoginTapped:)
                          forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_m_containerView];
    
#if DEBUG
//    self.m_containerView.m_cCodeTextF.text = @"A93jie957lK";
//    self.m_containerView.m_userNameTextF.text = @"kevin";
//    self.m_containerView.m_passwordTextF.text = @"aaa";
//    self.m_containerView.m_cCodeTextF.text = @"211534962";
//    self.m_containerView.m_userNameTextF.text = @"alexander";
//    self.m_containerView.m_passwordTextF.text = @"1";
    self.m_containerView.m_cCodeTextF.text = @"211534962";
    self.m_containerView.m_userNameTextF.text = @"admin";
    self.m_containerView.m_passwordTextF.text = @"thoradmin";

    
    
    [self.m_containerView checkLoginEnable];
#else
    
#endif
}

#pragma mark - Logic


#pragma mark - Actions
- (void)onBGTapped:(__unused id)sender {
    [self.view endEditing:YES];
}

- (void)onLoginTapped:(__unused id)sender {
//    
    NSString *nsRegisterCode = self.m_containerView.m_cCodeTextF.text;
    NSString *nsUserName = self.m_containerView.m_userNameTextF.text;
    NSString *nsPassword = [self.m_containerView.m_passwordTextF.text uppercaseMD5String];
//        NSString *nsRegisterCode = @"211534962";
//        NSString *nsUserName = @"admin";
//        NSString *nsPassword = @"thoradmin";
   
    
    void(^succ)(id) = ^(id data) {
        ICRUserUtil *userUtil = [ICRUserUtil sharedInstance];
        userUtil.bAutoLogin = @( [_m_containerView isAutoLogin] );
        [userUtil saveArchive];
        
        ICRAppViewControllerManager *mgr =
        [ICRAppViewControllerManager getAppViewControllerManager];
        [mgr openMainFrame];
        
        
#pragma 可以开新线程 ，待优化
        //当登陆成功时就建立功能数据表
        [[GXFFunctionDB sharedInstance]createTables];
        
        //完成对初始化数据书库的操作
        if (![[GXFFunctionDBHelper sharedInstance] successInsertOriginFunctions]) {
            [[GXFFunctionDBHelper sharedInstance] insertAllOriginFunctions];
        }
        if (![[GXFFunctionDBHelper sharedInstance] sucessInsertOriginDisplayFunctions]) {
            [[GXFFunctionDBHelper sharedInstance] insertAllOriginDisplayFunctions];
        }
        

        
        //更改功能权限
        for (int count = 0; count < userUtil.permissions.count; count ++) {
            GXFFunction *function = [[GXFFunctionDB sharedInstance]functionSelectWithId:[userUtil.permissions[count] integerValue]];
            if (function.Id) {
                function.hasPermission = 1;
                [[GXFFunctionDB sharedInstance] updateFunctionHasPermissionWithId:function];
            }
        }
        
        if (![[GXFFunctionDB sharedInstance]defaultdisplayFunctions]) {
            [[GXFFunctionDB sharedInstance]defaultdisplayFunctions];
        }
        
        
        
    };
    
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView showTips:data];
    };
    ICRHTTPController *httpCtrl = [ICRHTTPController sharedController];
    [httpCtrl doLoginWithUserName:nsUserName
                         password:nsPassword
                     registerCode:nsRegisterCode
                          success:succ
                          failure:fail];
}

#pragma mark - TextObserver
- (void)inputTextEditChanged:(NSNotification *)obj {
    [self.m_containerView checkLoginEnable];
}

#pragma mark - Keyboard
- (void)keyboardWillShow:(NSNotification *)note {
    // get keyboard size and loctaion
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // Need to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    
    // animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
    // set views with new info
    self.m_containerView.y = - 50.0f;
    
    // commit animations
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)note {
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
    // set views with new info
    self.m_containerView.y = m_fDefaultContainerY;
    
    // commit animations
    [UIView commitAnimations];
}

@end
