//
//  RegisterViewController.m
//  LifeLog
//
//  Created by Panasonic R&D Center Vietnam on 7/31/17.
//  Copyright © 2017 PhongNV. All rights reserved.
//

#import "RegisterViewController.h"
#import "CustomTextField.h"
#import "Utilities.h"
#import "NSDate+helper.h"
#import "ServerAPI.h"
#import "AppDelegate.h"
static int const kPickerTagArea = 1;
static int const kPickerTagSex = 2;

@interface RegisterViewController ()<UIActionSheetDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate>
{
    NSInteger indexArea;
    UIPickerView *pickerArea;
  
    UIPickerView *pickerSex;
    UIDatePicker *pickerDate;
    NSDate *dateBirthDay;
    NSString *profile_image;
}
@property (nonatomic, weak) IBOutlet UIImageView *avatar;

@property (nonatomic, weak) IBOutlet UILabel *lblUsername;
@property (nonatomic, weak) IBOutlet UILabel *lblName;
@property (nonatomic, weak) IBOutlet UILabel *lblNickname;
@property (nonatomic, weak) IBOutlet UILabel *lblEmail;
@property (nonatomic, weak) IBOutlet UILabel *lblPassword;
@property (nonatomic, weak) IBOutlet UILabel *lblConfirmPassword;
@property (nonatomic, weak) IBOutlet UILabel *lblSex;
@property (nonatomic, weak) IBOutlet UILabel *lblBirthday;
@property (nonatomic, weak) IBOutlet UILabel *lblHeight;
@property (nonatomic, weak) IBOutlet UILabel *lblHeightUnit;
@property (nonatomic, weak) IBOutlet UILabel *lblWeight;
@property (nonatomic, weak) IBOutlet UILabel *lblWeightUnit;
@property (nonatomic, weak) IBOutlet UILabel *lblFatPercentage;
@property (nonatomic, weak) IBOutlet UILabel *lblFatPercentageUnit;
@property (nonatomic, weak) IBOutlet UILabel *lblPhysicalActivity;
@property (nonatomic, weak) IBOutlet UILabel *lblArea;
@property (nonatomic, weak) IBOutlet UILabel *lblNote;

@property (nonatomic, weak) IBOutlet UITextField *tfUsername;
@property (nonatomic, weak) IBOutlet UITextField *tfName;
@property (nonatomic, weak) IBOutlet UITextField *tfNickname;
@property (nonatomic, weak) IBOutlet UITextField *tfEmail;
@property (nonatomic, weak) IBOutlet UITextField *tfPassword;
@property (nonatomic, weak) IBOutlet UITextField *tfConfirmPassword;
@property (nonatomic, weak) IBOutlet UITextField *tflblSex;
@property (nonatomic, weak) IBOutlet UITextField *tfBirthday;
@property (nonatomic, weak) IBOutlet UITextField *tfHeight;
@property (nonatomic, weak) IBOutlet UITextField *tfWeight;
@property (nonatomic, weak) IBOutlet UITextField *tfFatPercentage;
@property (nonatomic, weak) IBOutlet UISegmentedControl *physicalActivity;
@property (nonatomic, weak) IBOutlet CustomTextField *tfArea;
@property (nonatomic, weak) IBOutlet UITextView *tvNote;

@property (nonatomic, weak) IBOutlet UIToolbar *toolBar;
@property (nonatomic, strong) NSArray *arrayArea;
@property (nonatomic, strong) NSArray *arraySex;

@property (nonatomic) UIImagePickerController *imagePickerController;

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUIRegister];
    
    _arrayArea = [[NSArray alloc] initWithObjects:@"北海道", @"青森県", @"岩手県", @"宮城県", @"秋田県", @"山形県", @"福島県", @"茨城県", @"栃木県", @"群馬県", @"埼玉県", @"千葉県", @"東京都", @"神奈川県", @"新潟県", @"富山県", @"石川県", @"福井県", @"山梨県", @"長野県", @"岐阜県", @"静岡県", @"愛知県", @"三重県", @"滋賀県", @"京都府", @"大阪府", @"兵庫県", @"奈良県", @"和歌山県", @"鳥取県", @"島根県", @"岡山県", @"広島県", @"山口県", @"徳島県", @"香川県", @"愛媛県", @"高知県", @"福岡県", @"佐賀県", @"長崎県", @"熊本県", @"大分県" , @"宮崎県", @"鹿児島県", @"沖縄県", nil];
    _arraySex = [[NSArray alloc] initWithObjects:@"男", @"女", nil];
  
    pickerArea = [[UIPickerView alloc] init];
    pickerArea.dataSource = self;
    pickerArea.delegate = self;
    pickerArea.showsSelectionIndicator = YES;
    pickerArea.tag = kPickerTagArea;
    pickerArea.backgroundColor = [Utilities convertHecToColor:0x618DB6];
    
    _tfArea.inputAccessoryView = _toolBar;
    _tfArea.inputView = pickerArea;
    //_tfArea.alpha = 0.5;
    _tfArea.delegate = self;
  
    pickerSex = [[UIPickerView alloc] init];
    pickerSex.dataSource = self;
    pickerSex.delegate = self;
    pickerSex.showsSelectionIndicator = YES;
    pickerSex.tag = kPickerTagSex;
    pickerSex.backgroundColor = [Utilities convertHecToColor:0x618DB6];
  
    _tflblSex.inputAccessoryView = _toolBar;
    _tflblSex.inputView = pickerSex;
    //_tflblSex.alpha = 0.5;
    _tflblSex.delegate = self;
  
    pickerDate = [[UIDatePicker alloc] init];
    pickerDate.backgroundColor = [Utilities convertHecToColor:0x618DB6];
    pickerDate.datePickerMode = UIDatePickerModeDate;
    _tfBirthday.inputAccessoryView = _toolBar;
    _tfBirthday.inputView = pickerDate;
    //_tflblSex.alpha = 0.5;
    _tflblSex.delegate = self;
    profile_image = @"";
}

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

- (void)setupUIRegister
{
    self.avatar.backgroundColor = [UIColor whiteColor];
    self.avatar.layer.borderWidth = 2.0f;
    self.avatar.layer.borderColor = [[UIColor whiteColor] CGColor];
    self.avatar.layer.cornerRadius = self.avatar.frame.size.width/2.0f;
    self.avatar.layer.masksToBounds = YES;
    self.title = NSLocalizedString(@"lifelog.register.title", nil);
    self.lblUsername.text = NSLocalizedString(@"lifelog.register.username", nil);
    self.lblName.text = NSLocalizedString(@"lifelog.register.name", nil);
    self.lblNickname.text = NSLocalizedString(@"lifelog.register.nickname", nil);
    self.lblEmail.text = NSLocalizedString(@"lifelog.common.email", nil);
    self.lblPassword.text = NSLocalizedString(@"lifelog.common.password", nil);
    self.lblConfirmPassword.text = NSLocalizedString(@"lifelog.register.confirmation.password", nil);
    self.lblSex.text = NSLocalizedString(@"lifelog.register.sex", nil);
    self.lblBirthday.text = NSLocalizedString(@"lifelog.register.birthday", nil);
    self.lblHeight.text = NSLocalizedString(@"lifelog.register.height", nil);
    self.lblHeightUnit.text = NSLocalizedString(@"lifelog.register.height.unit", nil);
    self.lblWeight.text = NSLocalizedString(@"lifelog.register.weight", nil);
    self.lblWeightUnit.text = NSLocalizedString(@"lifelog.register.weight.unit", nil);
    self.lblFatPercentage.text = NSLocalizedString(@"lifelog.register.fat.percentage", nil);
    self.lblFatPercentageUnit.text = NSLocalizedString(@"lifelog.register.fat.percentage.unit", nil);
    self.lblPhysicalActivity.text = NSLocalizedString(@"lifelog.register.daily.physical.activity.level", nil);
    self.lblArea.text = NSLocalizedString(@"lifelog.register.area", nil);
    self.lblNote.text = NSLocalizedString(@"lifelog.register.note", nil);
  
    UIImage *img1=[UIImage imageNamed:@"icon_right"];
    CGRect frameimg1 = CGRectMake(0, 0, img1.size.width, img1.size.height);
    UIButton *registButton=[[UIButton alloc]initWithFrame:frameimg1];
    [registButton setBackgroundImage:img1 forState:UIControlStateNormal];
    [registButton addTarget:self action:@selector(registButtonPressed:)
                  forControlEvents:UIControlEventTouchUpInside];
    [registButton setShowsTouchWhenHighlighted:YES];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithCustomView:registButton];
    self.navigationItem.rightBarButtonItem = barButton;
}

#pragma mark - Actions
- (IBAction)avatarTouchUpInside:(id)sender {
    UIActionSheet *action = [[UIActionSheet alloc] initWithTitle:@"Avatar" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"Select Camera", @"Select Photo", nil];
    [action showInView:self.view];
}

- (IBAction)registButtonPressed:(id)sender {
    if ([self checkAllowRegister]) {
        [self registerUser];
    }
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 0:
            [self showCamera];
            break;
        case 1:
            [self showPhoto];
            break;
        default:
            break;
    }
}

#pragma mark - UIImagePickerControllerDelegate

// This method is called when an image has been chosen from the library or taken from the camera.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
    //NSData *imageData = UIImageJPEGRepresentation (image, 0.5);
    
    // My image view is 90x90
    //UIImage *thumbImage = MyCreateThumbnailImageFromData(imageData, 90);
    UIImage *thumbImage = [self imageWithImage:image scaledToFillSize:CGSizeMake(80, 80)];
    
    self.avatar.image = thumbImage;
    NSData *dataImage = UIImagePNGRepresentation(thumbImage);
    RegisterViewController __weak *weakSelf = self;
    [[ServerAPI server] uploadImage:nil andImageData:dataImage CompletionHandler:^(NSString *linkImage, NSError *error) {
        if (weakSelf == nil) {
            return ;
        }
        if (error == nil) {
            profile_image = linkImage;
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *message = [error.userInfo objectForKey:@"message"];
                [Utilities showErrorMessage:message withViewController:weakSelf];
            });
        }
    }];
    // Dismiss the image picker.
    [self dismissViewControllerAnimated:YES completion:nil];
    _imagePickerController = nil;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
  [self dismissViewControllerAnimated:YES completion:^{
    //.. done dismissing
  }];
}

- (UIImage *)imageWithImage:(UIImage *)image scaledToFillSize:(CGSize)size
{
    CGFloat scale = MAX(size.width/image.size.width, size.height/image.size.height);
    CGFloat width = image.size.width * scale;
    CGFloat height = image.size.height * scale;
    CGRect imageRect = CGRectMake((size.width - width)/2.0f,
                                  (size.height - height)/2.0f,
                                  width,
                                  height);
    
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    [image drawInRect:imageRect];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

#pragma mark - Function Private
- (void)showCamera {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.modalPresentationStyle = UIModalPresentationCurrentContext;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePickerController.delegate = self;
        imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
        _imagePickerController = imagePickerController; // we need this for later
        [self presentViewController:self.imagePickerController animated:YES completion:^{
            //.. done presenting
        }];
    }
}

- (void)showPhoto {
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.modalPresentationStyle = UIModalPresentationCurrentContext;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePickerController.delegate = self;
    imagePickerController.modalPresentationStyle = UIModalPresentationPopover;
    _imagePickerController = imagePickerController; // we need this for later
    [self presentViewController:self.imagePickerController animated:YES completion:^{
        //.. done presenting
    }];
}

- (void)showImagePickerForSourceType:(UIImagePickerControllerSourceType)sourceType fromButton:(UIBarButtonItem *)button
{
    if (self.avatar.isAnimating)
    {
        [self.avatar stopAnimating];
    }
  
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.modalPresentationStyle = UIModalPresentationCurrentContext;
    imagePickerController.sourceType = sourceType;
    imagePickerController.delegate = self;
    imagePickerController.modalPresentationStyle =
    (sourceType == UIImagePickerControllerSourceTypeCamera) ? UIModalPresentationFullScreen : UIModalPresentationPopover;
  
    UIPopoverPresentationController *presentationController = imagePickerController.popoverPresentationController;
    presentationController.barButtonItem = button;  // display popover from the UIBarButtonItem as an anchor
    presentationController.permittedArrowDirections = UIPopoverArrowDirectionAny;
  
    if (sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        // The user wants to use the camera interface. Set up our custom overlay view for the camera.
        imagePickerController.showsCameraControls = NO;
    
        /*
        Load the overlay view from the OverlayView nib file. Self is the File's Owner for the nib file, so the overlayView outlet is set to the main view in the nib. Pass that view to the image picker controller to use as its overlay view, and set self's reference to the view to nil.
         */
    }
  
    _imagePickerController = imagePickerController; // we need this for later
  
    [self presentViewController:self.imagePickerController animated:YES completion:^{
        //.. done presenting
    }];
}

- (IBAction)donePicker:(id)sender
{
    [_tfArea resignFirstResponder];
    [_tflblSex resignFirstResponder];
    if ([_tfBirthday becomeFirstResponder]) {
        [_tfBirthday resignFirstResponder];
        dateBirthDay = pickerDate.date;
        _tfBirthday.text = [NSString stringWithFormat:@"%ld%@%ld%@%ld%@", (long)[dateBirthDay getYear], NSLocalizedString(@"lifelog.common.year", nil), (long)[dateBirthDay getMonth], NSLocalizedString(@"lifelog.common.month", nil), (long)[dateBirthDay getDay], NSLocalizedString(@"lifelog.common.day", nil)];
    }
}

#pragma mark - UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField {
    //if (textField == _tfArea) {
        [textField resignFirstResponder];
    //}
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //if (textField == _tfArea) {
        [textField resignFirstResponder];
        return NO;
    //}
    //else {
        return YES;
    //}
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    //if (textField == _tfArea) {
        [textField resignFirstResponder];
    //}
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    //if (textField == _tfArea) {
        [textField resignFirstResponder];
    //}
    return YES;
}

#pragma mark - UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    int tag = (int)pickerView.tag;
    switch (tag) {
        case kPickerTagArea:
            return _arrayArea.count;
        case kPickerTagSex:
            return _arraySex.count;
        default:
            return 0;
    }
}

#pragma mark - UIPickerViewDelegate
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    int tag = (int)pickerView.tag;
    switch (tag) {
        case kPickerTagArea:
            _tfArea.text = [_arrayArea objectAtIndex:row];
            break;
        case kPickerTagSex:
            _tflblSex.text = [_arraySex objectAtIndex:row];
        break;
        default:
            break;
    }
}

- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *strTitle = @"";
    int tag = (int)pickerView.tag;
    switch (tag) {
        case kPickerTagArea:
            strTitle = [_arrayArea objectAtIndex:row];
            break;
        case kPickerTagSex:
            strTitle = [_arraySex objectAtIndex:row];
        break;
        default:
            strTitle = @"";
            break;
    }
    NSAttributedString *attString = [[NSAttributedString alloc] initWithString:strTitle attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    return attString;
    
}

- (NSMutableDictionary *)addParam:(NSString *)param value:(NSString *)value withDict:(NSMutableDictionary *)dict
{
    if (value.length > 0) {
        [dict setObject:value forKey:param];
    }
    return dict;
}

- (BOOL)checkAllowRegister
{
    NSString *message = @"";
    if (_tfUsername.text.length <= 0) {
        message = @"Please input username";
        [Utilities showErrorMessage:message withViewController:self];
        return NO;
    }
    if (_tfName.text.length <= 0) {
        message = @"Please input full name";
        [Utilities showErrorMessage:message withViewController:self];
        return NO;
    }
    if (_tfEmail.text.length <= 0) {
        message = @"Please input email";
        [Utilities showErrorMessage:message withViewController:self];
        return NO;
    }
    if (_tfPassword.text.length <= 0) {
        message = @"Please input password";
        [Utilities showErrorMessage:message withViewController:self];
        return NO;
    }
    if (_tfConfirmPassword.text.length <= 0) {
        message = @"Please input confirm password";
        [Utilities showErrorMessage:message withViewController:self];
        return NO;
    }
    if (_tflblSex.text.length <= 0) {
        message = @"Please input gender";
        [Utilities showErrorMessage:message withViewController:self];
        return NO;
    }
    if (_tfUsername.text.length > 100) {
        message = @"Username maximum length 100";
        [Utilities showErrorMessage:message withViewController:self];
        return NO;
    }
    if (_tfName.text.length > 255) {
        message = @"Full name maximum length 255";
        [Utilities showErrorMessage:message withViewController:self];
        return NO;
    }
    if (_tfEmail.text.length > 255) {
        message = @"Email maximum length 255";
        [Utilities showErrorMessage:message withViewController:self];
        return NO;
    }
    if (_tfPassword.text.length < 6) {
        message = @"Password minimum length 6";
        [Utilities showErrorMessage:message withViewController:self];
        return NO;
    }
    if (![_tfEmail.text containsString:@"@"]) {
        message = @"Email invalid";
        [Utilities showErrorMessage:message withViewController:self];
        return NO;
    }
    return YES;
}

- (NSDictionary *)createParamsForRegisterUser {
    NSMutableDictionary *dictResutl = [[NSMutableDictionary alloc] init];
    dictResutl = [self addParam:@"username" value:_tfUsername.text withDict:dictResutl];
    dictResutl = [self addParam:@"full_name" value:_tfName.text withDict:dictResutl];
    dictResutl = [self addParam:@"nickname" value:_tfNickname.text withDict:dictResutl];
    dictResutl = [self addParam:@"email" value:_tfEmail.text withDict:dictResutl];
    dictResutl = [self addParam:@"password" value:_tfPassword.text withDict:dictResutl];
    dictResutl = [self addParam:@"password_confirmation" value:_tfConfirmPassword.text withDict:dictResutl];
    // 0 - 男, 1 - 女 // NSString *valueSex = nil;
    if (_tflblSex.text.length > 0) {
        if ([_tflblSex.text isEqualToString:@"男"]) {
            [dictResutl setValue:[NSNumber numberWithInt:0] forKey:@"gender"];
        }
        else if ([_tflblSex.text isEqualToString:@"女"]) {
            [dictResutl setValue:[NSNumber numberWithInt:1] forKey:@"gender"];
        }
    }
    //dictResutl = [self addParam:@"gender" value:valueSex withDict:dictResutl];
    NSString *valueBirthDay = nil;
    if (_tfBirthday.text.length > 0) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        valueBirthDay = [dateFormatter stringFromDate:dateBirthDay];
        //valueBirthDay = [NSString stringWithFormat:@"%ld-%ld-%ld", (long)[dateBirthDay getYear], (long)[dateBirthDay getMonth], (long)[dateBirthDay getDay]];
        dictResutl = [self addParam:@"birthday" value:valueBirthDay withDict:dictResutl];
    }
    dictResutl = [self addParam:@"height" value:_tfHeight.text withDict:dictResutl];
    dictResutl = [self addParam:@"weight" value:_tfWeight.text withDict:dictResutl];
    dictResutl = [self addParam:@"fat_rate" value:_tfFatPercentage.text withDict:dictResutl];
    NSString *physicalActivityValue = [NSString stringWithFormat:@"%ld", _physicalActivity.selectedSegmentIndex];
    dictResutl = [self addParam:@"physical_activity" value:physicalActivityValue withDict:dictResutl];
    dictResutl = [self addParam:@"address" value:_tfArea.text withDict:dictResutl];
    dictResutl = [self addParam:@"description" value:_tvNote.text withDict:dictResutl];
    if (![profile_image isEqualToString:@""]) {
        dictResutl = [self addParam:@"profile_image" value:profile_image withDict:dictResutl];
    }
    // hardcode
    // require
    [dictResutl setValue:[NSNumber numberWithInt:0] forKey:@"receive_notification"];
    // = [self addParam:@"receive_notification" value:@"0" withDict:dictResutl];
    [dictResutl setValue:[NSNumber numberWithInt:0] forKey:@"share_data"];
    // dictResutl = [self addParam:@"share_data" value:@"0" withDict:dictResutl];
  
    // Option
    //dictResutl = [self addParam:@"phone" value:@"01676582596" withDict:dictResutl];
    [dictResutl setValue:[NSNumber numberWithInt:0] forKey:@"remember_me"];
    //dictResutl = [self addParam:@"remember" value:@"0" withDict:dictResutl];
  
    return dictResutl;
}

- (void)registerUser {
    NSDictionary *paramRegister = [self createParamsForRegisterUser];
    RegisterViewController __weak *weakSelf = self;
    [[ServerAPI server] registerUserWithParams:paramRegister CompletionHandler:^(User *user, NSString *token, NSError *error) {
        if (weakSelf == nil) {
            return ;
        }
        if (error == nil) {
            // For Saving
            NSData *dataSave = [NSKeyedArchiver archivedDataWithRootObject:user];
            [[NSUserDefaults standardUserDefaults] setObject:dataSave forKey:kUser];
            [[NSUserDefaults standardUserDefaults] setObject:token forKey:kToken];
            [[NSUserDefaults standardUserDefaults] synchronize];
            dispatch_async(dispatch_get_main_queue(), ^{
                [[AppDelegate sharedAppDelegate] gotoMainMenu];
            });
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *message = [error.userInfo objectForKey:@"message"];
                [Utilities showErrorMessage:message withViewController:weakSelf];
            });
        }
    }];
}

@end
