//
//  VisitorsVC.m
//  Gilliatte
//
//  Created by Lead on 12/08/16.
//  Copyright © 2016 Lead infosoft. All rights reserved.
//

#import "VisitorsVC.h"
#import "ActionSheetPicker.h"
#import "ActionSheetDatePicker.h"
#import "ApiUtillity.h"
#import "Base64.h"
#import "AFNetworking.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "VisitorsVC.h"
#import "VisitorsMainVC.h"


@import MobileCoreServices;

@interface VisitorsVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,UIPopoverControllerDelegate>{
    
    UIPopoverController *popover;
    NSDate *today;
    NSString *DateAndTime;
    NSString *VisitorName;
    
    NSString *UserTime;
    NSString *UserEditedTime;
    
    NSString *imageData;
    
    NSMutableArray *VisitorNameArray;
    NSMutableArray *VisitorTimeArray;
    
    NSMutableArray *getVisitorArray;
    
    //PopUp
    NSString *PopUpMainDateNTime;
    BOOL IsNSuser;
    
    BOOL isEdited;
    NSMutableArray *EditedArray;
    NSMutableArray *EditedNameArray;
    NSMutableArray *EditedTimeArray;
    BOOL IsBackCheck;
    BOOL IsDeleteCheck;
    
    NSString *DeleteRecordID;
}

@end

@implementation VisitorsVC
@synthesize delegate;

#pragma mark- ViewDidload
- (void)viewDidLoad {
    [super viewDidLoad];
    isEdited = 0;
    
    today = [NSDate date];
    self.selectedDate = today;
    
    VisitorName = [[NSString alloc]init];
    DateAndTime = [[NSString alloc]init];
    imageData = [[NSString alloc]init];
    
    _imageview_Upload.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGesture1 = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(tapGesture:)];
    tapGesture1.numberOfTapsRequired = 1;
    [_imageview_Upload addGestureRecognizer:tapGesture1];
    
    getVisitorArray = [[NSMutableArray alloc]init];
    VisitorNameArray = [[NSMutableArray alloc]init];
    VisitorTimeArray = [[NSMutableArray alloc]init];
    
    EditedArray = [[NSMutableArray alloc]init];
    EditedNameArray = [[NSMutableArray alloc]init];
    EditedTimeArray = [[NSMutableArray alloc]init];
    
 
   
    
    IsDeleteCheck=0;
    
    //    [self getVisitorData];
}

-(void)viewWillAppear:(BOOL)animated{
    NSLog(@"Call");
    
    [self getVisitorData];
    if ([_isEdited  isEqual: @"YES"]) {
        
        UserEditedTime = [_EditedArray valueForKey:@"visit_time"];
        if (![UserEditedTime isEqualToString:@""]) {
            [_btn_SelectDate setTitle:UserEditedTime forState:UIControlStateNormal];
            UserTime = UserEditedTime;
        }
        
        _txt_VisitorName.text = [_EditedArray valueForKey:@"name"];
        _textview_Write.text = [_EditedArray valueForKey:@"description"];
        DeleteRecordID = [_EditedArray valueForKey:@"id"];
        
        
        [_indicator startAnimating];
        NSString *img = [_EditedArray valueForKey:@"img"];
        [_imageview_Upload sd_setImageWithURL:[NSURL URLWithString:img] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            imageData = [self encodeToBase64String:_imageview_Upload.image];
            [_indicator stopAnimating];
        }];
    }
    else{
        _btn_Delete.hidden = true;
        [self.btn_Save.superview addConstraint:[NSLayoutConstraint
                                                constraintWithItem:self.btn_Save.superview
                                                attribute:NSLayoutAttributeCenterX
                                                relatedBy:NSLayoutRelationEqual
                                                toItem:self.btn_Save
                                                attribute:NSLayoutAttributeCenterX
                                                multiplier:1.0
                                                constant:0.0]];
        [_indicator stopAnimating];
        [_indicator hidesWhenStopped];
    }
    
    
}

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


#pragma mark- ButtonAction
- (IBAction)btn_bar_Back:(id)sender
{
    [self.navigationController popViewControllerAnimated:true];
    
}
- (IBAction)Btn_Handler_Delte_Actn:(id)sender {
    [self DeleteVisitorData];
    
}

- (IBAction)btn_Handler_Delete:(id)sender {
    //}
}



- (IBAction)btn_Handler_AddVisitor:(id)sender {
    //    isEdited = 0;
    VisitorName = @"";
    DateAndTime = @"";
    PopUpMainDateNTime = @"";
    _txt_PopUp_VisitorName.text = @"";
    [_btn_SelectDate setTitle:@"Select Time" forState:UIControlStateNormal];
    _view_PopUp.hidden = false;
}


- (IBAction)btn_Handler_SelectDate:(id)sender {
    [self.view endEditing:true];
    
    NSInteger minuteInterval = 1;
    //clamp date
    NSInteger referenceTimeInterval = (NSInteger)[self.selectedTime timeIntervalSinceReferenceDate];
    NSInteger remainingSeconds = referenceTimeInterval % (minuteInterval *60);
    NSInteger timeRoundedTo5Minutes = referenceTimeInterval - remainingSeconds;
    if(remainingSeconds>((minuteInterval*60)/2)) {/// round up
        timeRoundedTo5Minutes = referenceTimeInterval +((minuteInterval*60)-remainingSeconds);
    }
    
    self.selectedTime = [NSDate date];
    
    //    NSLocale *local = [[NSLocale alloc]initWithLocaleIdentifier:@"NL"];
    
    ActionSheetDatePicker *datePicker = [[ActionSheetDatePicker alloc] initWithTitle:@"Select a time" datePickerMode:UIDatePickerModeTime selectedDate:self.selectedTime target:self action:@selector(dateWasSelected:element:) origin:sender];
    datePicker.minuteInterval = minuteInterval;
   // [datePicker setMinimumDate:[NSDate date]];
    
    
    //    datePicker.locale = local;
    
    [datePicker showActionSheetPicker];
}


- (IBAction)btn_Handler_Cancel:(id)sender {
    //    isEdited = 1;
    _view_PopUp.hidden = true;
}


- (IBAction)btn_Handler_PopUpSave:(id)sender {
    _view_PopUp.hidden = true;
    if (isEdited == 0) {
        if (![_txt_PopUp_VisitorName.text isEqual: @""] && ![PopUpMainDateNTime isEqual: @""]) {
            VisitorName = _txt_PopUp_VisitorName.text;
            DateAndTime = PopUpMainDateNTime;
            
            if (![VisitorName  isEqual: @""] && DateAndTime != nil) {
                DateAndTime = [DateAndTime stringByAppendingString:@":00"];
                [VisitorNameArray addObject:VisitorName];
                [VisitorTimeArray addObject:DateAndTime];
                [_tableview_PrevUserDetail reloadData];
            }
            else{
                return;
            }
        }
    }
    else{
        if (![_txt_PopUp_VisitorName.text isEqual: @""] && ![PopUpMainDateNTime isEqual: @""]) {
            VisitorName = _txt_PopUp_VisitorName.text;
            DateAndTime = PopUpMainDateNTime;
            
            if (![VisitorName  isEqual: @""] && DateAndTime != nil) {
                DateAndTime = [DateAndTime stringByAppendingString:@":00"];
                
                [EditedNameArray addObject:VisitorName];
                [EditedTimeArray addObject:DateAndTime];
                [_tableview_PrevUserDetail reloadData];
            }
            else{
                return;
            }
        }
    }
    
}

- (IBAction)btn_Handler_Save:(id)sender {
    if ([_isEdited  isEqual: @"YES"]) {
        [self SendEditedVisitorData];
    }
    else{
        [self SendVisitorData];
    }
}


#pragma mark- All Methode
- (void)dateWasSelected:(NSDate *)selectedDate element:(id)element {
    self.selectedDate = selectedDate;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"hh:mm a"];
    
    NSString *DateSpilt = [[NSString alloc]init];
    NSString *Time = [dateFormatter stringFromDate:selectedDate];
    
    if ((DateSpilt = [[NSUserDefaults standardUserDefaults]objectForKey:@"SELECTED_DATE"]))
    {
        PopUpMainDateNTime = [[NSString alloc]init];
        //        PopUpMainDateNTime = [PopUpMainDateNTime stringByAppendingString:DateSpilt];
        //        PopUpMainDateNTime = [PopUpMainDateNTime stringByAppendingString:@" "];
        PopUpMainDateNTime = [PopUpMainDateNTime stringByAppendingString:Time];
        
        UserTime  = [[NSString alloc]init];
        UserTime = [NSString stringWithFormat:@"%@",PopUpMainDateNTime];
        [_btn_SelectDate setTitle:[NSString stringWithFormat:@"%@",PopUpMainDateNTime] forState:UIControlStateNormal];
    }
}

- (void) tapGesture: (id)sender
{
    
    NSLog(@"Check Hello");
    
    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_Upload;
    popPresenter.sourceRect = self.imageview_Upload.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_Upload.frame inView:self.imageview_Upload 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;
            //            picker.modalPresentationStyle = UIModalPresentationFullScreen;
            //            picker.mediaTypes = @[(NSString *) kUTTypeImage];
            
            [self presentViewController:picker animated:YES completion:NULL];
        }
    }
    
    
    
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
    self.imageview_Upload.image = chosenImage;
    imageData = [self encodeToBase64String:_imageview_Upload.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];
}



-(void)SendVisitorData{
    
    NSString *Date,*UID;
    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"]))
    {
        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;
    }
    else{
        return;
    }
    
    
    NSString *Desc,*Name,*Type,*ProID;
    
    if (!_textview_Write.text.length || [_textview_Write.text isEqualToString:@"Write Here..."])
    {
        UIAlertView *alert = [[UIAlertView alloc]init];
        alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please Enter Description." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    else
    {
        Desc = _textview_Write.text;
        
    }
    Type = @"visitor";
    
    if (!(ProID = [[NSUserDefaults standardUserDefaults] objectForKey:@"PROJECT_ID"]))
    {
        UIAlertView *alert = [[UIAlertView alloc]init];
        alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please Select Project." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    if (![_txt_VisitorName.text  isEqual: @""]) {
        Name = _txt_VisitorName.text;
    }
    else{
        return;
    }
    
    if (!UserTime.length) {
        [[[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please Select Time." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
        return;
    }
    
    /*
     NSString *VisitorNameS,*VisitorTimeS;
     VisitorNameS = [[NSString alloc]init];
     VisitorTimeS = [[NSString alloc]init];
     if (VisitorNameArray.count != 0 && VisitorTimeArray.count != 0) {
     int i;
     for (i = 0; i < VisitorNameArray.count; i++) {
     
     if (VisitorNameArray.count == 1) {
     VisitorNameS = [VisitorNameArray objectAtIndex:0];
     VisitorTimeS = [VisitorTimeArray objectAtIndex:0];
     }
     else{
     if (i == 0) {
     
     VisitorNameS = [VisitorNameArray objectAtIndex:0];
     VisitorNameS = [VisitorNameS stringByAppendingString:@","];
     
     VisitorTimeS = [VisitorTimeArray objectAtIndex:0];
     VisitorTimeS = [VisitorTimeS stringByAppendingString:@","];
     }
     else{
     if (VisitorNameArray.count-1 == i) {
     VisitorNameS = [VisitorNameS stringByAppendingString:[VisitorNameArray objectAtIndex:i]];
     
     VisitorTimeS = [VisitorTimeS stringByAppendingString:[VisitorTimeArray objectAtIndex:i]];
     }
     else{
     VisitorNameS = [VisitorNameS stringByAppendingString:[VisitorNameArray objectAtIndex:i]];
     VisitorNameS = [VisitorNameS stringByAppendingString:@","];
     
     VisitorTimeS = [VisitorTimeS stringByAppendingString:[VisitorTimeArray objectAtIndex:i]];
     VisitorTimeS = [VisitorTimeS stringByAppendingString:@","];
     
     }
     }
     
     }
     }
     }
     
     NSLog(@"%@",VisitorNameS);
     NSLog(@"%@",VisitorTimeS);*/
    
    
    [ApiUtillity setSVProgressHUDView:self.view];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager.requestSerializer setTimeoutInterval:150.0];

    NSDictionary *params = @{@"date":Date,@"uid":UID,@"photo":imageData,@"name":Name,@"description":Desc,@"type":Type,@"time":UserTime,@"project_id":ProID};
    
    [manager POST:@"http://p4bdesigns.com/Gilliatteweb/app/api3/record_add.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject != nil) {
            NSString *Suceess;
            if ((Suceess = [responseObject valueForKey:@"success"])) {
                NSLog(@"Visitor record created");
                
                NSMutableArray *record = [responseObject valueForKey:@"records"];
                [delegate getRecordArray:record];
                
                [ApiUtillity dissmissSVProgressHUDViewWithSuccess:self.view WithMessage:@"Record Added"];
                
//                VisitorsMainVC *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"VisitorsMainVC"];
//                [self.navigationController pushViewController:vc animated:true];
                
                [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)SendEditedVisitorData{
    NSString *Date,*UID,*ProID;
    NSString *Desc,*Name,*Type,*VisitorId;

    
    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"]))
    {
        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;
    }
    else{
        return;
    }
    
    
    if (!(ProID = [[NSUserDefaults standardUserDefaults] objectForKey:@"PROJECT_ID"]))
    {
        UIAlertView *alert = [[UIAlertView alloc]init];
        alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please Select Project." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    
    
    
    if (!_textview_Write.text.length || [_textview_Write.text isEqualToString:@"Write Here..."])
    {
        UIAlertView *alert = [[UIAlertView alloc]init];
        alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please Enter Description." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    else
    {
        Desc = _textview_Write.text;
        
    }
    
    VisitorId = [_EditedArray valueForKey:@"id"];
    Type = @"visitor";
    
    if (![_txt_VisitorName.text  isEqual: @""]) {
        Name = _txt_VisitorName.text;
    }
    else{
        return;
    }
    
    /*
     NSString *VisitorNameS,*VisitorTimeS;
     VisitorNameS = [[NSString alloc]init];
     VisitorTimeS = [[NSString alloc]init];
     if (EditedNameArray.count != 0 && EditedTimeArray.count != 0)
     {
     int i;
     for (i = 0; i < EditedNameArray.count; i++) {
     
     if (EditedNameArray.count == 1) {
     VisitorNameS = [EditedNameArray objectAtIndex:0];
     VisitorTimeS = [EditedTimeArray objectAtIndex:0];
     }
     else{
     if (i == 0) {
     
     VisitorNameS = [EditedNameArray objectAtIndex:0];
     VisitorNameS = [VisitorNameS stringByAppendingString:@","];
     
     if (EditedTimeArray.count != 1) {
     VisitorTimeS = [EditedTimeArray objectAtIndex:0];
     VisitorTimeS = [VisitorTimeS stringByAppendingString:@","];
     }
     }
     else{
     if (EditedNameArray.count-1 == i) {
     VisitorNameS = [VisitorNameS stringByAppendingString:[EditedNameArray objectAtIndex:i]];
     
     if (EditedTimeArray.count == 1) {
     VisitorTimeS = [EditedTimeArray objectAtIndex:0];
     }
     else{
     VisitorTimeS = [VisitorTimeS stringByAppendingString:[EditedTimeArray objectAtIndex:i]];
     }
     }
     else{
     if (EditedNameArray.count > i) {
     VisitorNameS = [VisitorNameS stringByAppendingString:[EditedNameArray objectAtIndex:i]];
     VisitorNameS = [VisitorNameS stringByAppendingString:@","];
     }
     if (EditedTimeArray.count > i && EditedTimeArray.count-1 != i) {
     VisitorTimeS = [VisitorTimeS stringByAppendingString:[EditedTimeArray objectAtIndex:i]];
     VisitorTimeS = [VisitorTimeS stringByAppendingString:@","];
     }
     }
     }
     }
     }
     }
     NSLog(@"%@",VisitorNameS);
     NSLog(@"%@",VisitorTimeS);*/
    
    
    [ApiUtillity setSVProgressHUDView:self.view];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager.requestSerializer setTimeoutInterval:150.0];

    
    NSDictionary *params = @{@"id":VisitorId,@"date":Date,@"uid":UID,@"photo":imageData,@"name":Name,@"description":Desc,@"type":Type,@"time":UserTime,@"project_id":ProID};
    
    
    [manager POST:@"http://p4bdesigns.com/Gilliatteweb/app/api3/record_add.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject != nil) {
            NSString *Suceess;
            if ((Suceess = [responseObject valueForKey:@"success"])) {
                NSLog(@"Visitor record Updated");
                
                NSMutableArray *record = [responseObject valueForKey:@"records"];
                [delegate getRecordArray:record];
                
                [ApiUtillity dissmissSVProgressHUDViewWithSuccess:self.view WithMessage:@"Record updated"];
                
//                VisitorsMainVC *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"VisitorsMainVC"];
//                [self.navigationController pushViewController:vc animated:true];
                
                [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 == 3840) {
            UIAlertView *alert = [[UIAlertView alloc]init];
            alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@" Error Domain" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
            [alert show];
        }
        
        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];
        }
        else{
            [ApiUtillity dissmissSVProgressHUDView:self.view];
        }
    }];
    
}


-(void) getVisitorData{
    NSString *Date,*UID,*Type;
    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;
    }
    
    
    Type = @"visitor";
    
    [ApiUtillity setSVProgressHUDView:self.view];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager.requestSerializer setTimeoutInterval:150.0];

    
    NSDictionary *params = @{@"date":Date,@"uid":UID,@"type":Type};
    
    [manager POST:@"http://p4bdesigns.com/Gilliatteweb/app/api3/record_get.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@",responseObject);
        if (responseObject != nil) {
            NSString *Suceess;
            if ((Suceess = [responseObject valueForKey:@"success"])) {
                if ([Suceess  isEqual: @"ok"]) {
                    //                    [ApiUtillity dissmissSVProgressHUDViewWithSuccess:self.view];
                    NSMutableArray *dataArray;
                    dataArray = [responseObject valueForKey:@"records"];
                    if (dataArray.count != 0) {
                        isEdited = 1;
                        getVisitorArray = [responseObject valueForKey:@"records"][0];
                        //                        for (NSMutableDictionary *Dic in dataArray) {
                        //                            [getVisitorArray addObject:Dic];
                        //                        }
                        
                        //Set image
                        [_indicator startAnimating];
                        NSString *img = [getVisitorArray valueForKey:@"img"];
                        [_imageview_Upload sd_setImageWithURL:[NSURL URLWithString:img] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                            [_indicator stopAnimating];
                            [_indicator hidesWhenStopped];
                            imageData = [self encodeToBase64String:_imageview_Upload.image];
                        }];
                        
                        //Set Name
                        _txt_VisitorName.text = [getVisitorArray valueForKey:@"name"];
                        
                        //ID
                      //  DeleteRecordID = [getVisitorArray valueForKey:@"id"];
                        
                        //description
                        _textview_Write.text = [getVisitorArray valueForKey:@"description"];
                        
                        EditedArray = [getVisitorArray valueForKey:@"visitors"];
                        
                        int i;
                        for (i = 0; i < EditedArray.count; i++) {
                            NSString *nameSplit,*TimeSplit;
                            nameSplit = [[EditedArray valueForKey:@"vname"]objectAtIndex:i];
                            TimeSplit = [[EditedArray valueForKey:@"vtime"]objectAtIndex:i];
                            
                            [EditedNameArray addObject:nameSplit];
                            [EditedTimeArray addObject:TimeSplit];
                        }
                        [_tableview_PrevUserDetail reloadData];
                        
                    }
                    else{
                        _btn_Delete.userInteractionEnabled = false;
                        [_indicator stopAnimating];
                        [_indicator hidesWhenStopped];
                    }
                }
            }
        }
        [ApiUtillity dissmissSVProgressHUDView:self.view];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        _btn_Delete.userInteractionEnabled = false;
        [_indicator stopAnimating];
        [_indicator hidesWhenStopped];
        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) DeleteVisitorData{
    
    [ApiUtillity setSVProgressHUDView:self.view];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager.requestSerializer setTimeoutInterval:150.0];

    NSDictionary *params = @{@"id":DeleteRecordID};
    
    [manager POST:@"http://p4bdesigns.com/Gilliatteweb/app/api3/record_delete.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject != nil) {
            NSString *Suceess;
            if ((Suceess = [responseObject valueForKey:@"success"])) {
                if ([Suceess  isEqual: @"Deleted"]) {
                    
                    //                    _txt_VisitorName.text=@"";
                    //                    _txt_PopUp_VisitorName.text=@"";
                    //                    [_btn_SelectDate setTitle:@"Select Time" forState:UIControlStateNormal];
                    //                    [_imageview_Upload setImage:[UIImage imageNamed:@"ic_Upload_Image2.png"]];
                    //
                    //                    [self getVisitorData];
                    
                    
                    IsDeleteCheck=1;
                    
                    [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];
        
    }];
}


//Encoding :--
- (NSString *)encodeToBase64String:(UIImage *)image {
    NSData* data = UIImageJPEGRepresentation(image, 1.0f);
    return [Base64 encode:data];
}


//Decoding :--
- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
    NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
    return [UIImage imageWithData:data];
}


#pragma mark - Textview Delegate
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    
    if ([_textview_Write.text  isEqual: @"Write Here..."]) {
        _textview_Write.text = @"";
        _textview_Write.textColor = [UIColor blackColor];
    }
    _textview_Write.textColor = [UIColor blackColor];
    return YES;
}

-(void)textViewDidChange:(UITextView *)textView{
    if (_textview_Write.text.length == 0) {
        _textview_Write.textColor = [UIColor lightGrayColor];
        _textview_Write.text = @"Write Here...";
        [_textview_Write resignFirstResponder];
    }
}


#pragma mark- Tableview Methode
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (isEdited == 0) {
        return VisitorNameArray.count;
    }
    else{
        return EditedNameArray.count;
    }
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //cellWeather
    static NSString *Indentifier = @"cellVisitorMain";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Indentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Indentifier];
    }
    
    UILabel *Name = [cell viewWithTag:1];
    UILabel *Time = [cell viewWithTag:2];
    
    if (isEdited == 0) {
        Name.text = [VisitorNameArray objectAtIndex:indexPath.row];
        Time.text = [VisitorTimeArray objectAtIndex:indexPath.row];
    }
    else{
        if (EditedNameArray.count > indexPath.row) {
            Name.text = [EditedNameArray objectAtIndex:indexPath.row];
        }
        if (EditedTimeArray.count > indexPath.row) {
            Time.text = [EditedTimeArray objectAtIndex:indexPath.row];
        }
        else{
            Time.text = @"";
        }
    }
    
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%ld",(long)indexPath.row);
    if (indexPath.row == 0) {
        
    }
}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        if (isEdited == 0) {
            NSLog(@"%ld %ld",(unsigned long)VisitorNameArray.count,(unsigned long)VisitorTimeArray.count);
            [VisitorNameArray removeObjectAtIndex:indexPath.row];
            [VisitorTimeArray removeObjectAtIndex:indexPath.row];
        }
        else{
            NSLog(@"%ld %ld",(unsigned long)EditedNameArray.count,(unsigned long)EditedTimeArray.count);
            if (EditedNameArray.count > indexPath.row) {
                [EditedNameArray removeObjectAtIndex:indexPath.row];
            }
            if (EditedTimeArray.count > indexPath.row) {
                [EditedTimeArray removeObjectAtIndex:indexPath.row];
            }
        }
        
        
        [_tableview_PrevUserDetail beginUpdates];
        [_tableview_PrevUserDetail deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
        [_tableview_PrevUserDetail endUpdates];
        
        NSLog(@"NameArray :-%@",VisitorNameArray);
        NSLog(@"MobileArray :-%@",VisitorTimeArray);
        //        [_tableview_PrevUserDetail reloadData];
    }
}

@end