//
//  SettingVC.m
//  Gilliatte
//
//  Created by Lead on 05/10/16.
//  Copyright © 2016 Lead infosoft. All rights reserved.
//

#import "SettingVC.h"
#import "ApiUtillity.h"
#import "HomeVC.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "AFNetworking.h"
#import "Base64.h"

@interface SettingVC ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate,UIPopoverControllerDelegate>{
    
    NSMutableArray *UserDataArray;
    UIPopoverController *popover;
    NSString *imageData;
}

@end

@implementation SettingVC


#pragma mark- ViewDidload
- (void)viewDidLoad {
    [super viewDidLoad];
    
    imageData = [[NSString alloc]init];
    UserDataArray = [[NSMutableArray alloc]init];
    
    NSData *GetUserData;
    if ((GetUserData = [[NSUserDefaults standardUserDefaults] objectForKey:@"USER_PROFILE"])) {
        NSMutableArray *savedArray = [NSKeyedUnarchiver unarchiveObjectWithData:GetUserData];
        NSMutableArray *UserArray = [[NSMutableArray alloc]init];
        UserArray = savedArray;
        
        NSLog(@"%@",UserArray);
        NSString *UserImage = [NSString stringWithFormat:@"%@",[UserArray valueForKey:@"profile_pic"]];
        NSString *UserName = [NSString stringWithFormat:@"%@",[UserArray valueForKey:@"name"]];
        NSString *UserEmail = [NSString stringWithFormat:@"%@",[UserArray valueForKey:@"email"]];
        
        [_ActivityIndicator startAnimating];
        [_imageview_User sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",UserImage]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            [_ActivityIndicator stopAnimating];
        }];
        
        _textfield_Name.text = UserName;
        _textfield_Email.text = UserEmail;
    }
    
    _imageview_User.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGesture1 = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(tapGesture:)];
    tapGesture1.numberOfTapsRequired = 1;
    [_imageview_User addGestureRecognizer:tapGesture1];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated{
    [[self navigationController] setNavigationBarHidden:NO animated:YES];
    [ApiUtillity setTransculantNavigation:self.navigationController];
    
    self.imageview_User.layer.cornerRadius = self.imageview_User.frame.size.width / 2.0f;
    self.imageview_User.layer.borderWidth = 1.0f;
    self.imageview_User.layer.borderColor = [UIColor blackColor].CGColor;
    self.imageview_User.clipsToBounds = YES;
}


#pragma mark- All Methode
-(void) sendProfileData{
    
    NSString *Date,*UID,*Name,*Email,*Password;
    NSData *GetUserData;
    if ((GetUserData = [[NSUserDefaults standardUserDefaults] objectForKey:@"USER_PROFILE"])) {
        NSMutableArray *savedArray = [NSKeyedUnarchiver unarchiveObjectWithData:GetUserData];
        NSMutableArray *UserArray = [[NSMutableArray alloc]init];
        UserArray = savedArray;
        
        NSLog(@"%@",UserArray);
        UID = [NSString stringWithFormat:@"%@",[UserArray valueForKey:@"uid"]];
    }
    
    if (!(Date = [[NSUserDefaults standardUserDefaults] objectForKey:@"SELECTED_DATE"]))
    {
        return;
    }
    else{
        NSArray *DateSeperate = [Date componentsSeparatedByString:@"/"];
        NSString *Day,*Month,*Year,*OriginalDate;
        OriginalDate = [[NSString alloc]init];
        Day = [DateSeperate objectAtIndex:0];
        Month = [DateSeperate objectAtIndex:1];
        Year = [DateSeperate objectAtIndex:2];
        
        OriginalDate = [OriginalDate stringByAppendingString:Year];
        OriginalDate = [OriginalDate stringByAppendingString:@"-"];
        OriginalDate = [OriginalDate stringByAppendingString:Month];
        OriginalDate = [OriginalDate stringByAppendingString:@"-"];
        OriginalDate = [OriginalDate stringByAppendingString:Day];
        
        Date = OriginalDate;
    }
    
    Name = _textfield_Name.text;
    Email = _textfield_Email.text;
    Password = _textfield_Password.text;
    
    [ApiUtillity setSVProgressHUDView:self.view];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager.requestSerializer setTimeoutInterval:150.0];

    
    NSDictionary *params = @{@"uid":UID,@"name":Name,@"email":Email,@"password":Password,@"profile_pic":imageData};
    
    [manager POST:@"http://p4bdesigns.com/Gilliatteweb/app/api3/update_user.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject != nil) {
            NSString *Suceess;
            if ((Suceess = [responseObject valueForKey:@"success"])) {
                NSLog(@"Profile updated");
                
                NSMutableArray *TempArray;
                if ((TempArray = [responseObject valueForKey:@"user"])) {
                    UserDataArray = TempArray;
                    NSLog(@"%@",UserDataArray);
                    NSData *SaveUserData = [NSKeyedArchiver archivedDataWithRootObject:UserDataArray];
                    [[NSUserDefaults standardUserDefaults] setObject:SaveUserData forKey:@"USER_PROFILE"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
                
                [ApiUtillity dissmissSVProgressHUDViewWithSuccess:self.view WithMessage:@"Record updated"];
                [self.navigationController popViewControllerAnimated:true];
            }
        }
        [ApiUtillity dissmissSVProgressHUDView:self.view];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        NSInteger statusCode = error.code;
        NSLog(@"%d",(int)statusCode);
        
        if(statusCode == -1001) {
            // request timed out
            NSLog(@"request timed out");
            [ApiUtillity setSVProgressHUDInfoView:self.view];
        }
        else if (statusCode == -1005){
            [ApiUtillity setSVProgressHUDInfoView:self.view];
        }
        else if (statusCode == -1009 || statusCode == -1004) {
            // no internet connectivity
            NSLog(@"No Internet Connection");
            UIAlertView *alert = [[UIAlertView alloc]init];
            alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"No Internet Connection" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
            [alert show];
        }
        [ApiUtillity dissmissSVProgressHUDView:self.view];
        
    }];
    
}

- (void) tapGesture: (id)sender
{
    UIActionSheet *actionSheetPop;
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"Upload Image" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    
    [actionSheet addAction:[UIAlertAction actionWithTitle:@"Gallery" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self actionSheet:actionSheetPop clickedButtonAtIndex:0];
    }]];
    
    [actionSheet addAction:[UIAlertAction actionWithTitle:@"Camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self actionSheet:actionSheetPop clickedButtonAtIndex:1];
    }]];
    
    [actionSheet addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }]];
    
    UIPopoverPresentationController *popPresenter = [actionSheet
                                                     popoverPresentationController];
    popPresenter.sourceView = self.imageview_User;
    popPresenter.sourceRect = self.imageview_User.frame;
    [self presentViewController:actionSheet animated:YES completion:nil];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"%ld",(long)buttonIndex);
    
    if (buttonIndex == 0) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
            popover.delegate = self;
            popover=[[UIPopoverController alloc]initWithContentViewController:picker];
            [popover presentPopoverFromRect:self.imageview_User.frame inView:self.imageview_User permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
            
        }
        else{
            [self presentViewController:picker animated:YES completion:NULL];
        }
    }
    else if (buttonIndex == 1){
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = YES;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            
            [self presentViewController:picker animated:YES completion:NULL];
        }
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
    self.imageview_User.image = chosenImage;
    
    imageData = [self encodeToBase64String:_imageview_User.image];
    
    if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        [popover dismissPopoverAnimated:YES];
        [picker dismissViewControllerAnimated:YES completion:nil];
    } else {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:NULL];
}
//Encoding :--
- (NSString *)encodeToBase64String:(UIImage *)image {
    NSData* data = UIImageJPEGRepresentation(image, 1.0f);
    return [Base64 encode:data];
}



#pragma mark- ButtonAction
- (IBAction)btn_bar_SideMenu:(id)sender {
    SlideMenuController *slideMenuController = self.slideMenuController;
    if (slideMenuController != nil) {
        [self.slideMenuController openLeft];
    }
}

- (IBAction)btn_Handler_Update:(id)sender {
    
    if ([_textfield_Name.text isEqualToString:@""]) {
        return;
    }
    if ([_textfield_Email.text isEqualToString:@""]) {
        return;
    }
    NSString *emailExpression = @"[A-Z0-9a-z._]+@[A-Z0-9a-z_.]+\\.[A-Za-z]{2,3}";
    NSPredicate *emailPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",emailExpression];
    if ([emailPredicate evaluateWithObject:_textfield_Email.text] != true) {
        return;
    }
    if ([_textfield_Password.text isEqualToString:@""])
    {
      
    }
    if ([_textfield_ConfirmPassword.text isEqualToString:@""])
    {
       
    }
    if (![_textfield_Password.text isEqualToString:_textfield_ConfirmPassword.text])
    {
        return;
        
    }
    
    //CALL API...
    [self sendProfileData];
}


- (IBAction)btn_Handler_Logout:(id)sender
{
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"PROJECT_ID"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"JOB_ID"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SUB_ID"];


    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"USER_PROFILE"];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    HomeVC *VC = (HomeVC *)[storyboard instantiateViewControllerWithIdentifier:@"HomeVC"];
    [self.navigationController pushViewController:VC animated:true];
}

@end
