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

#import "WorkPerformedVC.h"
#import "ActionSheetPicker.h"
#import "AFNetworking.h"
#import "ApiUtillity.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "Base64.h"
//#import "ELCImagePickerDemoAppDelegate.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import "WorkPerformedMainVC.h"
#import "AddCompanyImageCell.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import <QuartzCore/QuartzCore.h>
#import "UIImageView+UIActivityIndicatorForSDWebImage.h"
#import "WorkPerformedMainVC.h"
#import "ConnectToServer.h"
#import "UIView+Toast.h"






@interface WorkPerformedVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,UIPopoverControllerDelegate,ConnectToServerDelegate>{
    NSInteger SelectedProject;
    NSInteger SelectedJob;
    NSInteger SelectedSub;
    NSInteger SelectedEmployee;
    
    NSMutableArray *ProjectArray;
    NSMutableArray *EmployeeArray;
    NSMutableArray *SubArray;
    NSMutableArray *UserDataArray;
    NSMutableArray *JobArray;
    NSMutableArray *ImagesDataArray;
    
    UIPopoverController *popover;
    NSString *imageData;
    UIImage *scaledimage;
    NSString *ImageName;
    NSString *ImagePreviewLink;
    
    
    BOOL isSelectProfile;
    BOOL isUpdateProfile;
    NSUInteger isSetProfile;
}

@property (nonatomic, strong) ALAssetsLibrary *specialLibrary;

@end

@implementation WorkPerformedVC
@synthesize delegate;

#pragma mark- ViewDidload
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //    SelectedProject = 0;
    //    SelectedJob = 0;
    //    SelectedSub = 0;
    //    SelectedEmployee = 0;
    
    ImagesDataArray=[[NSMutableArray alloc]init];
    imageData = [[NSString alloc]init];
    JobArray = [[NSMutableArray alloc]init];
    UserDataArray = [[NSMutableArray alloc]init];
    ProjectArray = [[NSMutableArray alloc]init];
    EmployeeArray = [[NSMutableArray alloc]init];
    SubArray = [[NSMutableArray alloc]init];
    
    _imageview_Upload.userInteractionEnabled = NO;
    _scroll_view.userInteractionEnabled=YES;
    _indicator.hidden=true;
    
    
    UITapGestureRecognizer *tapGesture1 = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(tapGesture:)];
    tapGesture1.numberOfTapsRequired = 1;
    [_scroll_view addGestureRecognizer:tapGesture1];
    
    
    if ([_isEdited  isEqual: @"YES"])
    {
        _btn_Job.userInteractionEnabled=false;
        _btn_Sub.userInteractionEnabled=false;
        _btn_Project.userInteractionEnabled=false;

        
        _textview_Write.text = [_EditedArray valueForKey:@"description"];
        
               for (NSString *str in [_EditedArray valueForKey:@"images"])
               {
                   NSArray *languagesuserArray = [str componentsSeparatedByString:@"/"];
                   
                [ImagesDataArray addObject:@{@"is_link":[languagesuserArray lastObject],@"image":str}];
            
        }
        
        [ImagesDataArray addObject:@{}];
        
        
        [_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{
        [ImagesDataArray addObject:@{}];
        [_indicator stopAnimating];
        [_indicator hidesWhenStopped];
    }
}

-(void)viewWillAppear:(BOOL)animated{
    SelectedProject = [ApiUtillity getProjectNumber];
    SelectedJob = [ApiUtillity getJobNumber];
    SelectedSub = [ApiUtillity getSubNumber];
    SelectedEmployee = [ApiUtillity getEmployeeNumber];
    
    //    [self GetMainData];
    [self getUserDefaultData];
}

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


#pragma mark- ButtonAction
- (IBAction)btn_bar_Back:(id)sender
{
//    WorkPerformedMainVC *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"WorkPerformedMainVC"];
//    [self.navigationController pushViewController:vc animated:true];
//    
    [self.navigationController popViewControllerAnimated:true];
}
- (IBAction)btn_Handler_Project:(id)sender {
    NSLog(@"%@",ProjectArray);
    NSMutableArray *ProjectSubArray = [[NSMutableArray alloc]init];
    NSArray *Project = [[NSArray alloc]init];
    int i;
    for (i=0; i<ProjectArray.count; i++) {
        [ProjectSubArray addObject:[[ProjectArray objectAtIndex:i]valueForKey:@"project_name"]];
    }
    Project = ProjectSubArray;
    [ActionSheetStringPicker showPickerWithTitle:@"Select Project"
                                            rows:Project
                                initialSelection:SelectedProject
                                       doneBlock:^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
                                           NSLog(@"Picker: %@, Index: %ld, value: %@",
                                                 picker, (long)selectedIndex, selectedValue);
                                           SelectedProject = selectedIndex;
                                           SelectedJob = 0;
                                           
                                           //Set Project Title
                                           [_btn_Project setTitle:[NSString stringWithFormat:@"%@", selectedValue] forState:UIControlStateNormal];
                                           
                                           //Set Sub Title
                                           SubArray = [[ProjectArray objectAtIndex:selectedIndex]valueForKey:@"subs"];
                                           
                                           if (SubArray.count > 0)
                                           {
                                               
                                              
                                               
                                                [_btn_Sub setTitle:[[SubArray objectAtIndex:0] valueForKey:@"name"] forState:UIControlStateNormal];
                                           }
                                           else
                                           {
                                               [_btn_Sub setTitle:@"Sub" forState:UIControlStateNormal];
                                               [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SUB_ID"];
                                               
                                               
                                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                                               message:@"No Subs Available For This Project."
                                                                                              delegate:self
                                                                                     cancelButtonTitle:@"OK"
                                                                                     otherButtonTitles:nil];
                                               [alert show];
                                               return;
                                               
                                           }
                                          
                                           
                                           
                                           //Set UserDefault Project_ID
                                           NSString *ProjectId = [[ProjectArray objectAtIndex:selectedIndex]valueForKey:@"project_id"];
                                           [[NSUserDefaults standardUserDefaults] setObject:ProjectId forKey:@"PROJECT_ID"];
                                           
                                           //Set UserDefault SUB_ID
                                           
                                            if (SubArray.count > 0)
                                            {
                                                
                                                
                                                NSString *SubID = [[SubArray objectAtIndex:0]valueForKey:@"id"];
                                                [[NSUserDefaults standardUserDefaults] setObject:SubID forKey:@"SUB_ID"];
                                            }
                                          
                                       }
                                     cancelBlock:^(ActionSheetStringPicker *picker) {
                                         NSLog(@"Block Picker Canceled");}
                                          origin:sender];
}
- (IBAction)btn_Handler_Job:(id)sender {
    NSArray *Job = [[NSArray alloc]init];
    NSMutableArray *JobSubArray = [[NSMutableArray alloc]init];
    //    JobArray = [[ProjectArray objectAtIndex:SelectedProjectB]valueForKey:@"jobs"];
    int i;
    for (i=0; i<JobArray.count; i++) {
        [JobSubArray addObject:[[JobArray objectAtIndex:i] valueForKey:@"job_title"]];
    }
    Job = JobSubArray;
    [ActionSheetStringPicker showPickerWithTitle:@"Select Job"
                                            rows:Job
                                initialSelection:SelectedJob
                                       doneBlock:^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
                                           NSLog(@"Picker: %@, Index: %ld, value: %@",
                                                 picker, (long)selectedIndex, selectedValue);
                                           SelectedJob = selectedIndex;
                                           [_btn_Job setTitle:[NSString stringWithFormat:@"%@", selectedValue] forState:UIControlStateNormal];
                                           
                                           //Set UserDefault JOb_Id
                                           //                                           NSString *JobId = [[JobArray objectAtIndex:selectedIndex]valueForKey:@"job_id"];
                                           //                                           [[NSUserDefaults standardUserDefaults] setObject:JobId forKey:@"JOB_ID"];
                                       }
                                     cancelBlock:^(ActionSheetStringPicker *picker) {
                                         NSLog(@"Block Picker Canceled");
                                     }
                                          origin:sender];
}
- (IBAction)btn_Handler_Sub:(id)sender {
    NSArray *Sub = [[NSArray alloc]init];
    NSMutableArray *SubNameArray = [[NSMutableArray alloc]init];
    int i;
    for (i=0; i<SubArray.count; i++) {
        [SubNameArray addObject:[[SubArray objectAtIndex:i] valueForKey:@"name"]];
    }
    Sub = SubNameArray;
    
     if (SubArray.count <= 0)
     {
         return;
         
     }
    [ActionSheetStringPicker showPickerWithTitle:@"Select Sub"
                                            rows:Sub
                                initialSelection:SelectedSub
                                       doneBlock:^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
                                           if (SubArray.count > 0)
                                           {
                                               
                                               
                                               
                                               NSLog(@"Picker: %@, Index: %ld, value: %@",
                                                     picker, (long)selectedIndex, selectedValue);
                                               SelectedSub = selectedIndex;
                                               
                                               
                                               [_btn_Sub setTitle:[NSString stringWithFormat:@"%@", selectedValue] forState:UIControlStateNormal];
                                               
                                               //Set UserDefault Sub_Id
                                               NSString *SubId = [[SubArray objectAtIndex:selectedIndex]valueForKey:@"id"];
                                               [[NSUserDefaults standardUserDefaults] setObject:SubId forKey:@"SUB_ID"];
                                           }
                                          
                                       }
                                     cancelBlock:^(ActionSheetStringPicker *picker) {
                                         NSLog(@"Block Picker Canceled");
                                     }
                                          origin:sender];
}
- (IBAction)btn_Handler_Employee:(id)sender {
    if (EmployeeArray.count == 0) {
        UIAlertView *alert = [[UIAlertView alloc]init];
        alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Doesn't get Employee" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    
    NSArray *Employee = [[NSArray alloc]init];
    NSMutableArray *EmpNameArray = [[NSMutableArray alloc]init];
    int i;
    for (i=0; i<EmployeeArray.count; i++) {
        [EmpNameArray addObject:[[EmployeeArray objectAtIndex:i] valueForKey:@"name"]];
    }
    Employee = EmpNameArray;
    [ActionSheetStringPicker showPickerWithTitle:@"Select Employee"
                                            rows:Employee
                                initialSelection:SelectedEmployee
                                       doneBlock:^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
                                           NSLog(@"Picker: %@, Index: %ld, value: %@",
                                                 picker, (long)selectedIndex, selectedValue);
                                           SelectedEmployee = selectedIndex;
                                           [_btn_Employee setTitle:[NSString stringWithFormat:@"%@", selectedValue] forState:UIControlStateNormal];
                                           
                                           //Set UserDefault Employee_Id
                                           NSString *EmployeeId = [[EmployeeArray objectAtIndex:selectedIndex]valueForKey:@"id"];
                                           [[NSUserDefaults standardUserDefaults] setObject:EmployeeId forKey:@"EMPLOYEE_ID"];
                                       }
                                     cancelBlock:^(ActionSheetStringPicker *picker) {
                                         NSLog(@"Block Picker Canceled");
                                     }
                                          origin:sender];
}

- (IBAction)btn_Handler_Save:(id)sender {
    
    if ([_isEdited  isEqual: @"YES"]) {
        [self sendEditedWorkPerformData];
    }
    else{
        [self sendWorkPerformData];
    }
}
- (IBAction)btn_Handler_DeleteImage:(id)sender
{
    UIButton *btn = (UIButton*)sender;
    [ImagesDataArray removeObjectAtIndex:btn.tag];
    [_collectonview_Image reloadData];
}



#pragma mark- All Methode
- (void) GetMainData{
    [ApiUtillity setSVProgressHUDView:self.view];
    NSString *UID = [[NSString 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);
        UID = [NSString stringWithFormat:@"%@",[UserArray valueForKey:@"uid"]];
    }
    NSString *Token;
    NSString *UUID;
    
    if ((Token = [[NSUserDefaults standardUserDefaults] objectForKey:@"PUSH_TOKEN"]) && (UUID = [[NSUserDefaults standardUserDefaults] objectForKey:@"UUID"])) {
    }
    //IF RUN IPHONE DEVICE
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    
    
    [manager.requestSerializer setTimeoutInterval:150.0];

    
    NSDictionary *params = @{@"uid": UID,@"dev_type":@"1",@"dev_token":Token,@"code":UUID};
    
    [manager POST:@"http://p4bdesigns.com/Gilliatteweb/app/api3/get_initial.php?" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if (responseObject != nil) {
            NSString *SuccessString;
            if ((SuccessString = [responseObject valueForKey:@"success"])) {
                if ([SuccessString isEqualToString:@"ok"]) {
                    UserDataArray = [responseObject valueForKey:@"user"];
                    NSLog(@"%@",UserDataArray);
                    
                    NSData *SaveUserData = [NSKeyedArchiver archivedDataWithRootObject:UserDataArray];
                    [[NSUserDefaults standardUserDefaults] setObject:SaveUserData forKey:@"USER_PROFILE"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    
                    ProjectArray = [responseObject valueForKey:@"projects"];
                    EmployeeArray = [responseObject valueForKey:@"employees"];
                    SubArray = [responseObject valueForKey:@"subs"];
                    
                    //SET PROJECT AND JOB DATA...
                    NSString *TempProjectID,*TempJobID,*TempEmployeeID,*TempSubID;
                    
                    if ((TempProjectID = [[NSUserDefaults standardUserDefaults]objectForKey:@"PROJECT_ID"]) && (TempJobID = [[NSUserDefaults standardUserDefaults]objectForKey:@"JOB_ID"]) && (TempSubID = [[NSUserDefaults standardUserDefaults]objectForKey:@"SUB_ID"]) && (TempEmployeeID = [[NSUserDefaults standardUserDefaults]objectForKey:@"EMPLOYEE_ID"])) {
                        int TempproID = [TempProjectID intValue];
                        int TempjobID = [TempJobID intValue];
                        int TempsubID = [TempSubID intValue];
                        int TempempID = [TempEmployeeID intValue];
                        
                        //FOR Project & Job...
                        int i;
                        for (i=0; i<ProjectArray.count; i++) {
                            NSString *proID,*jobID;
                            proID = [[ProjectArray objectAtIndex:i] valueForKey:@"project_id"];
                            if ([proID intValue] == TempproID) {
                                //SET UI DATA
                                [_btn_Project setTitle:[[ProjectArray objectAtIndex:i]valueForKey:@"project_name"] forState:UIControlStateNormal];
                                JobArray = [[ProjectArray objectAtIndex:i]valueForKey:@"jobs"];
                                int x;
                                for (x=0; x<JobArray.count; x++) {
                                    jobID = [[JobArray objectAtIndex:x] valueForKey:@"job_id"];
                                    if ([jobID intValue] == TempjobID) {
                                        [_btn_Job setTitle:[[JobArray objectAtIndex:x] valueForKey:@"job_title"] forState:UIControlStateNormal];
                                    }
                                }
                            }
                        }
                        
                        //For Employee...
                        int x;
                        for (x=0; x<EmployeeArray.count; x++) {
                            NSString *empID;
                            empID = [[EmployeeArray objectAtIndex:x] valueForKey:@"id"];
                            if ([empID intValue] == TempempID) {
                                //SET UI DATA
                                [_btn_Employee setTitle:[[EmployeeArray objectAtIndex:x]valueForKey:@"name"] forState:UIControlStateNormal];
                            }
                        }
                        
                        //For Sub...
                        int y;
                        for (y=0; y<SubArray.count; y++) {
                            NSString *subID;
                            subID = [[SubArray objectAtIndex:y] valueForKey:@"id"];
                            if ([subID intValue] == TempsubID) {
                                //SET UI DATA
                                [_btn_Sub setTitle:[[SubArray objectAtIndex:y]valueForKey:@"name"] forState:UIControlStateNormal];
                            }
                        }
                    }
                }
            }
        }
        [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) getUserDefaultData{
    ProjectArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"ProjectArray"];
    SubArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"SubArray"];
    
    //SET PROJECT AND JOB DATA...
    NSString *TempProjectID,*TempJobID,*TempSubID;
    
    if ((TempProjectID = [[NSUserDefaults standardUserDefaults]objectForKey:@"PROJECT_ID"])) {
        int TempproID = [TempProjectID intValue];
        int TempjobID = [TempJobID intValue];
        NSLog(@"TempJobid :--- %d",TempjobID);
        
        
        //FOR Project & Job...
        int i;
        for (i=0; i<ProjectArray.count; i++) {
            NSString *proID,*subID;
            proID = [[ProjectArray objectAtIndex:i] valueForKey:@"project_id"];
            if ([proID intValue] == TempproID) {
                //SET UI DATA
                [_btn_Project setTitle:[[ProjectArray objectAtIndex:i]valueForKey:@"project_name"] forState:UIControlStateNormal];
                SubArray = [[ProjectArray objectAtIndex:i]valueForKey:@"subs"];
                
                if ((TempSubID = [[NSUserDefaults standardUserDefaults]objectForKey:@"SUB_ID"])) {
                    int TempsubID = [TempSubID intValue];
                    int x;
                    for (x=0; x<SubArray.count; x++) {
                        subID = [[SubArray objectAtIndex:x] valueForKey:@"id"];
                        if ([subID intValue] == TempsubID){
                            //SET UI DATA
                            [_btn_Sub setTitle:[[SubArray objectAtIndex:x] valueForKey:@"name"] forState:UIControlStateNormal];
                        }
                    }
                }
            }
        }
    }
    
    /*
     if ((TempEmployeeID = [[NSUserDefaults standardUserDefaults]objectForKey:@"EMPLOYEE_ID"])) {
     //For Employee...
     int TempempID = [TempEmployeeID intValue];
     int x;
     for (x=0; x<EmployeeArray.count; x++) {
     NSString *empID;
     empID = [[EmployeeArray objectAtIndex:x] valueForKey:@"id"];
     if ([empID intValue] == TempempID) {
     //SET UI DATA
     [_btn_Employee setTitle:[[EmployeeArray objectAtIndex:x]valueForKey:@"name"] forState:UIControlStateNormal];
     }
     }
     }
     
     if ((TempSubID = [[NSUserDefaults standardUserDefaults]objectForKey:@"SUB_ID"])) {
     //For Sub...
     int TempsubID = [TempSubID intValue];
     int y;
     for (y=0; y<SubArray.count; y++) {
     NSString *subID;
     subID = [[SubArray objectAtIndex:y] valueForKey:@"id"];
     if ([subID intValue] == TempsubID) {
     //SET UI DATA
     [_btn_Sub setTitle:[[SubArray objectAtIndex:y]valueForKey:@"name"] forState:UIControlStateNormal];
     }
     }
     }*/
    
}

-(void) sendWorkPerformData{
    NSString *ProID,*JobID,*EmpID,*SubID,*Date,*UID,*Desc,*Type;
    NSData *GetUserData;
    NSMutableArray *ImageData;
    
    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;
    }
    
    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 ((!(JobID = [[NSUserDefaults standardUserDefaults] objectForKey:@"JOB_ID"]))) {
        JobID = @"-1";
    }
    if ((!(SubID = [[NSUserDefaults standardUserDefaults] objectForKey:@"SUB_ID"]))) {
        UIAlertView *alert = [[UIAlertView alloc]init];
        alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please Select Sub." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    if (!(EmpID = [[NSUserDefaults standardUserDefaults] objectForKey:@"EMPLOYEE_ID"]))
    {
        EmpID = @"-1";
        //        UIAlertView *alert = [[UIAlertView alloc]init];
        //        alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please Select Employee." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        //        [alert show];
        //        return;
    }
    if ([_textview_Write.text  isEqual: @""] || [_textview_Write.text  isEqual: @"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;
    }
    if (!ImagesDataArray.count) {
        [ImagesDataArray addObject:@""];
    }
    
    [ImagesDataArray removeLastObject];
    if (ImagesDataArray.count) {
        ImageData = [[NSMutableArray alloc]initWithArray:[ImagesDataArray valueForKey:@"is_link"]];
    }
    else{
        ImageData = [[NSMutableArray alloc]initWithArray:@[]];
    }
    
    Type = @"work_performed";
    
    
    [ApiUtillity setSVProgressHUDView:self.view];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.requestSerializer setTimeoutInterval:150.0];
    NSDictionary *params = @{@"date":Date,@"uid":UID,@"project_id":ProID,@"job_id":JobID,@"emp_id":EmpID,@"sub_id":SubID,@"photo":ImageData,@"description":Desc,@"type":Type};
    NSLog(@"Param:--- %@",params);

    
//    ConnectToServer *objService=[[ConnectToServer alloc]init];
//    objService.delegate=self;
//    [objService CallPostWithUrlForProfile:[NSString stringWithFormat:@"%@",@"http://p4bdesigns.com/Gilliatteweb/app/api2/record_add.php"] andDataDictionary:[params mutableCopy] andImages:ImageData];
//
    
    
    [manager POST:@"http://p4bdesigns.com/Gilliatteweb/app/api3/record_add.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject != nil)
        {
            NSLog(@"Param:--- %@",responseObject);

            NSString *Suceess;
            if ((Suceess = [responseObject valueForKey:@"success"])) {
                NSLog(@"Work_performed record created");
                
                NSMutableArray *record = [responseObject valueForKey:@"records"];
                [delegate getRecordArray:record];
                
                //Set UserDefault Emp_Id & Sub_Id
                [_btn_Sub setTitle:@"Sub" forState:UIControlStateNormal];
                [_btn_Employee setTitle:@"Employee" forState:UIControlStateNormal];
                
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"SUB_ID"];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"EMPLOYEE_ID"];
                
                [ApiUtillity dissmissSVProgressHUDViewWithSuccess:self.view WithMessage:@"Record Added"];
                
//                WorkPerformedMainVC *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"WorkPerformedMainVC"];
//                [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);
        NSString *Status1=[NSString stringWithFormat:@"%ld",(long)statusCode];
        //[self.view makeToast:Status1 duration:3.0 position:CSToastPositionTop];
        
        
        
        if(statusCode == -1001) {
            // request timed out
            NSLog(@"request timed out");
            [ApiUtillity setSVProgressHUDInfoView:self.view];
            
            
           // [self sendWorkPerformData];
        }
        else if (statusCode == -1005){
          [ApiUtillity setSVProgressHUDInfoView:self.view];
           // [self sendWorkPerformData];

        }
        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];
        }
        else{
           // [self sendWorkPerformData];

            [ApiUtillity dissmissSVProgressHUDView:self.view];
        }
    }];
    
    
}

-(void) sendEditedWorkPerformData{
    
    
    
    NSString *ProID,*JobID,*EmpID,*SubID,*Date,*UID,*Desc,*Type,*RecordId;
    NSData *GetUserData;
    NSMutableArray *ImageData;
    
    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;
    }
    
    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 ((!(JobID = [[NSUserDefaults standardUserDefaults] objectForKey:@"JOB_ID"]))) {
        JobID = @"-1";
    }
    if ((!(SubID = [[NSUserDefaults standardUserDefaults] objectForKey:@"SUB_ID"]))) {
        UIAlertView *alert = [[UIAlertView alloc]init];
        alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please Select Sub." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    if ([_textview_Write.text  isEqual: @""] || [_textview_Write.text  isEqual: @"Write Here..."]) {
        return;
    }
    else{
        Desc = _textview_Write.text;
    }
    
    if (!ImagesDataArray.count) {
        [ImagesDataArray addObject:@""];
    }
    
    [ImagesDataArray removeLastObject];
    if (ImagesDataArray.count) {
        ImageData = [[NSMutableArray alloc]initWithArray:[ImagesDataArray valueForKey:@"is_link"]];
    }
    else{
        ImageData = [[NSMutableArray alloc]initWithArray:@[]];
    }
    
    ProID = [_EditedArray valueForKey:@"project_id"];
    JobID = [_EditedArray valueForKey:@"job_id"];
    JobID = @"-1";
    EmpID = [_EditedArray valueForKey:@"emp_id"];
    SubID = [_EditedArray valueForKey:@"sub_id"];
    RecordId = [_EditedArray valueForKey:@"id"];
    Type = @"work_performed";
    
    [ApiUtillity setSVProgressHUDView:self.view];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager.requestSerializer setTimeoutInterval:150.0];

    
    NSDictionary *params = @{@"id":RecordId,@"date":Date,@"uid":UID,@"project_id":ProID,@"job_id":JobID,@"emp_id":EmpID,@"sub_id":SubID,@"photo":ImageData,@"description":Desc,@"type":Type};
    NSLog(@"Param:--- %@",params);
    
    
    [manager POST:@"http://p4bdesigns.com/Gilliatteweb/app/api3/record_add.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject != nil) {
            NSLog(@"Param:--- %@",responseObject);

            
            NSString *Suceess;
            if ((Suceess = [responseObject valueForKey:@"success"])) {
                NSLog(@"Work_performed record updated");
                
                NSMutableArray *record = [responseObject valueForKey:@"records"];
                [delegate getRecordArray:record];
                
                //Set UserDefault Emp_Id & Sub_Id
                [_btn_Sub setTitle:@"Sub" forState:UIControlStateNormal];
                [_btn_Employee setTitle:@"Employee" forState:UIControlStateNormal];
                
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"SUB_ID"];
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"EMPLOYEE_ID"];
                
                [ApiUtillity dissmissSVProgressHUDViewWithSuccess:self.view WithMessage:@"Record updated"];
                
//                WorkPerformedMainVC *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"WorkPerformedMainVC"];
//                [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];
        
    }];
    
}


//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];
}

- (void) tapGesture: (id)sender
{
    
    ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initImagePicker];
    elcPicker.maximumImagesCount = 100; //Set the maximum number of images to select, defaults to 4
    elcPicker.returnsOriginalImage = NO; //Only return the fullScreenImage, not the fullResolutionImage
    elcPicker.returnsImage = YES; //Return UIimage if YES. If NO, only return asset location information
    elcPicker.onOrder = YES; //For multiple image selection, display and return selected order of images
    elcPicker.imagePickerDelegate = self;
    
    //Present modally
    [self presentViewController:elcPicker animated:YES completion:nil];
    
    
    
    /*
     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;
     
     [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)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info;
{
    _imageview_Upload.hidden=true;
    _imgview_2nd.hidden=true;
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    
    for (UIView *v in [_scroll_view subviews]) {
        [v removeFromSuperview];
    }
    
    CGRect workingFrame = _scroll_view.frame;
    workingFrame.origin.x = 0;
    
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:[info count]];
    for (NSDictionary *dict in info) {
        if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto){
            if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
                
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
                
                [ImagesDataArray addObject:[UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]];
                
                UIImageView *imageview = [[UIImageView alloc] initWithImage:image];
                [imageview setContentMode:UIViewContentModeScaleAspectFit];
                imageview.frame = workingFrame;
                
                [_scroll_view addSubview:imageview];
                
                workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width;
            } else {
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        } else if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypeVideo){
            if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
                
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
                
                UIImageView *imageview = [[UIImageView alloc] initWithImage:image];
                [imageview setContentMode:UIViewContentModeScaleAspectFit];
                imageview.frame = workingFrame;
                
                [_scroll_view addSubview:imageview];
                
                workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width;
            } else {
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        } else {
            NSLog(@"Uknown asset type");
        }
    }
    
    self.chosenImages = images;
    
    [_scroll_view setPagingEnabled:YES];
    [_scroll_view setContentSize:CGSizeMake(workingFrame.origin.x, workingFrame.size.height)];
}

- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker;
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)AddNewImage {
    isSetProfile = 0;
    
    UIAlertController *Alert = [UIAlertController alertControllerWithTitle:@"Select Image" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"Camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
        {
            AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
            if (status == AVAuthorizationStatusDenied) {
                
                UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"camera_access" message:@"permission_camera" preferredStyle:UIAlertControllerStyleAlert];
                [controller addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                }]];
                [controller addAction:[UIAlertAction actionWithTitle:@"Open" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                }]];
                
                [self presentViewController:controller animated:true completion:nil];
            }
            else{
                UIImagePickerController *imagePickController=[[UIImagePickerController alloc]init];
                imagePickController.sourceType=UIImagePickerControllerSourceTypeCamera;
                imagePickController.delegate=self;
                imagePickController.allowsEditing=TRUE;
                [self presentViewController:imagePickController animated:true completion:nil];
            }
        }
    }];
    UIAlertAction *Gallery = [UIAlertAction actionWithTitle:@"Gallery" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusDenied) {
            UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"photo_access" message:@"permission_photo" preferredStyle:UIAlertControllerStyleAlert];
            [controller addAction:[UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }]];
            [controller addAction:[UIAlertAction actionWithTitle:@"Open" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }]];
            
            [self presentViewController:controller animated:true completion:nil];
        }
        else{
            UIImagePickerController *imagePickController=[[UIImagePickerController alloc]init];
            imagePickController.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
            imagePickController.delegate=self;
            imagePickController.allowsEditing=TRUE;
            [self presentViewController:imagePickController animated:true completion:nil];
        }
    }];
    UIAlertAction *Cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [Alert addAction:camera];
    [Alert addAction:Gallery];
    [Alert addAction:Cancel];
    [self presentViewController:Alert animated:true completion:nil];
    
}

#pragma mark- Image Resizing Method


- (UIImage *)imageWithImage:(UIImage *)image convertToSize:(CGSize)size {
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *destImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return destImage;
}




#pragma mark- UIImagePickerController Methode
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    
    
 //   UIImage *img = [UIImage imageNamed:@"logo.png"];
    
    CGFloat width = image.size.width;
    CGFloat height = image.size.height;
    
    if (width > 1024 && height > 1024)
    {
        NSLog(@"");
        scaledimage=[self imageWithImage:image convertToSize:CGSizeMake(1000, 1000)];
        CGFloat width1 = scaledimage.size.width;
        CGFloat height1 = scaledimage.size.height;
        NSLog(@"Width Of Image:--- %f",width1);
        NSLog(@"height1 Of Image:--- %f",height1);

        

    }
    else
    {
        scaledimage=[info objectForKey:UIImagePickerControllerOriginalImage];
        CGFloat width1 = scaledimage.size.width;
        CGFloat height1 = scaledimage.size.height;
        NSLog(@"Width Of Image:--- %f",width1);
        NSLog(@"height1 Of Image:--- %f",height1);

        
        
    }
    
    if (isSetProfile == 1) {
        isSelectProfile = 1;
    }
    else{
        [self SendImageData];

    
    }
    
    [self dismissViewControllerAnimated:true completion:nil];
}

#pragma mark - Image Upload One By One Method

-(void) SendImageData{
    
    
    
    [ApiUtillity setSVProgressHUDView:self.view];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *params = @{@"photo":[UIImagePNGRepresentation(scaledimage) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]};
    
    [manager POST:@"http://p4bdesigns.com/Gilliatteweb/app/api3/upload_record_pic.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject != nil) {
            NSString *DataArray;
            if ((DataArray = [responseObject valueForKey:@"success"]))
            {
                NSLog(@"Weather record created");
//                name
//                preview
                ImageName = [responseObject valueForKey:@"name"];
                ImagePreviewLink=[responseObject valueForKey:@"preview"];
                
                [ImagesDataArray insertObject:@{@"is_link":ImageName,@"image":ImagePreviewLink} atIndex:ImagesDataArray.count-1];
                [_collectonview_Image reloadData];
                [_collectonview_Image scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:ImagesDataArray.count-1 inSection:0] atScrollPosition:UICollectionViewScrollPositionRight 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");
            [self SendImageData];
            //[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];
        
    }];
}


#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- CollectionView Methode
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [ImagesDataArray count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (ImagesDataArray.count-1 == indexPath.row) {
        AddCompanyImageCell *cell = [_collectonview_Image dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        
        [[cell.btn_Add layer] setBorderWidth:2.0f];
        [[cell.btn_Add layer] setBorderColor:[UIColor darkGrayColor].CGColor];
        [[cell.btn_Add layer] setCornerRadius:15.0f];
        cell.btn_Add.clipsToBounds = true;
        
        [cell.btn_Add addTarget:self action:@selector(AddNewImage) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
    else{
        AddCompanyImageCell *cell = [_collectonview_Image dequeueReusableCellWithReuseIdentifier:@"AddCompanyImageCell" forIndexPath:indexPath];
        [cell.btn_Delete addTarget:self action:@selector(btn_Handler_DeleteImage:) forControlEvents:UIControlEventTouchUpInside];
        cell.btn_Delete.tag = indexPath.row;
        
        
        NSString *temp = [[ImagesDataArray objectAtIndex:indexPath.row] valueForKey:@"is_link"];
        
        [cell.imageview_AddCompany setImageWithURL:[NSURL URLWithString:[[ImagesDataArray objectAtIndex:indexPath.row] valueForKey:@"image"]] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        
      
        
        return cell;
    }
}


#pragma mark - connection methods
- (void) onResultWithData:(NSDictionary *)responseData
{
    NSLog(@"Result------>%@",responseData);
}
- (void) onError
{
    NSLog(@"Error");
    
}

@end
