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

#import "WeatherVC.h"
#import "ActionSheetPicker.h"
#import "AFNetworking.h"
#import "ApiUtillity.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "Base64.h"
#import "WeatherMainVC.h"



@interface WeatherVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate, UIActionSheetDelegate,UIPopoverControllerDelegate>{
    NSInteger SelectedProject;
    NSInteger SelectedJob;
    
    NSMutableArray *ProjectArray;
    NSMutableArray *EmployeeArray;
    NSMutableArray *SubArray;
    NSMutableArray *UserDataArray;
    NSMutableArray *JobArray;
    
    UIPopoverController *popover;
    NSString *imageData;
    
}

@end

@implementation WeatherVC
@synthesize delegate;

#pragma mark- ViewDidload
- (void)viewDidLoad {
    [super viewDidLoad];
    
//    SelectedProject = 0;
//    SelectedJob = 0;
    
    imageData = [[NSString alloc]init];
    
    JobArray = [[NSMutableArray alloc]init];
    UserDataArray = [[NSMutableArray alloc]init];
    ProjectArray = [[NSMutableArray alloc]init];
    EmployeeArray = [[NSMutableArray alloc]init];
    SubArray = [[NSMutableArray alloc]init];
    
    _img_Upload.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGesture1 = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(tapGesture:)];
    tapGesture1.numberOfTapsRequired = 1;
    [_img_Upload addGestureRecognizer:tapGesture1];
    
   
}

-(void)viewWillAppear:(BOOL)animated{
    SelectedProject = [ApiUtillity getProjectNumber];
    SelectedJob = [ApiUtillity getJobNumber];
    
//    [self GetMainData];
    [self getUserDefaultData];
    
    if ([_isEdited  isEqual: @"YES"]) {
        _textview_Write.text = [_EditedArray valueForKey:@"description"];
        
        [_indicator startAnimating];
        NSString *img = [_EditedArray valueForKey:@"img"];
        [_img_Upload sd_setImageWithURL:[NSURL URLWithString:img] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            imageData = [self encodeToBase64String:_img_Upload.image];
            [_indicator stopAnimating];
            
            
            
            _btn_SelectedJob.userInteractionEnabled=false;
            _btn_SelectedProject.userInteractionEnabled=false;
            
            
            
        }];
    }
    else{
        [_indicator stopAnimating];
        [_indicator hidesWhenStopped];
    }
    
}

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

#pragma mark- ButtonAction
- (IBAction)btn_bar_Back:(id)sender
{
//    WeatherMainVC *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"WeatherMainVC"];
//    [self.navigationController pushViewController:vc animated:YES];
    
    [self.navigationController popViewControllerAnimated:true];
}

- (IBAction)btn_Handler_SelectProject:(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;
                                           
                                           [_btn_SelectedProject setTitle:[NSString stringWithFormat:@"%@", selectedValue] forState:UIControlStateNormal];
                                           //Set JOb Title
//                                           JobArray = [[ProjectArray objectAtIndex:selectedIndex]valueForKey:@"jobs"];
//                                           [_btn_SelectedJob setTitle:[[JobArray objectAtIndex:0] valueForKey:@"job_title"] forState:UIControlStateNormal];
                                           
                                           //Set UserDefault Project_ID
                                           NSString *ProjectId = [[ProjectArray objectAtIndex:selectedIndex]valueForKey:@"project_id"];
                                           [[NSUserDefaults standardUserDefaults] setObject:ProjectId forKey:@"PROJECT_ID"];
                                           //Set UserDefault JOb_Id
//                                           NSString *JobId = [[JobArray objectAtIndex:0]valueForKey:@"job_id"];
//                                           [[NSUserDefaults standardUserDefaults] setObject:JobId forKey:@"JOB_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_SelectedJob 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_Save:(id)sender {
    if ([_isEdited  isEqual: @"YES"]) {
        [self sendEditedWeatherData];
    }
    else{
        [self sendWeatherData];
    }
}


#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];
    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;
                    if ((TempProjectID = [[NSUserDefaults standardUserDefaults]objectForKey:@"PROJECT_ID"]) && (TempJobID = [[NSUserDefaults standardUserDefaults]objectForKey:@"JOB_ID"])) {
                        int TempproID = [TempProjectID intValue];
                        int TempjobID = [TempJobID intValue];
                        
                        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_SelectedProject 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_SelectedJob setTitle:[[JobArray objectAtIndex:x] valueForKey:@"job_title"] 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;
    if ((TempProjectID = [[NSUserDefaults standardUserDefaults]objectForKey:@"PROJECT_ID"])) {
        int TempproID = [TempProjectID intValue];
        int TempjobID = [TempJobID intValue];
        NSLog(@"TempjobID :-- %d",TempjobID);
        
        
        int i;
        for (i=0; i<ProjectArray.count; i++) {
            NSString *proID,*jobID;
            NSLog(@"jobID:-- %@",jobID);
            
            proID = [[ProjectArray objectAtIndex:i] valueForKey:@"project_id"];
            if ([proID intValue] == TempproID) {
                //SET UI DATA
                [_btn_SelectedProject 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_SelectedJob setTitle:[[JobArray objectAtIndex:x] valueForKey:@"job_title"] forState:UIControlStateNormal];
//                    }
//                }
            }
        }
    }
}

-(void) sendWeatherData{
    
    NSString *ProID,*JobID,*Date,*UID,*Desc,*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;
    }
    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 ([_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 (imageData == nil) {
        imageData = @"nil";
    }
    
    Type = @"weather";
    
    [ApiUtillity setSVProgressHUDView:self.view];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *params = @{@"date":Date,@"uid":UID,@"project_id":ProID,@"job_id":JobID,@"photo":imageData,@"description":Desc,@"type":Type};
    
    [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(@"Weather record created");
                
                NSMutableArray *record = [responseObject valueForKey:@"records"];
                [delegate getRecordArray:record];
                
                [ApiUtillity dissmissSVProgressHUDViewWithSuccess:self.view WithMessage:@"Record Added"];
                
                WeatherMainVC *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"WeatherMainVC"];
                [self.navigationController popViewControllerAnimated:vc];
                
                
               // [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) sendEditedWeatherData{
    
    NSString *ProID,*JobID,*Date,*UID,*Desc,*Type,*RecordId;
    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;
    }
    
    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 (imageData == nil) {
        imageData = @"nil";
    }
    
    ProID = [_EditedArray valueForKey:@"project_id"];
    JobID = [_EditedArray valueForKey:@"job_id"];
    JobID = @"-1";
    RecordId = [_EditedArray valueForKey:@"id"];
    Type = @"weather";
    
    [ApiUtillity setSVProgressHUDView:self.view];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *params = @{@"id":RecordId,@"date":Date,@"uid":UID,@"project_id":ProID,@"job_id":JobID,@"photo":imageData,@"description":Desc,@"type":Type};
    
    [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(@"Weather record updated");
                
                NSMutableArray *record = [responseObject valueForKey:@"records"];
                [delegate getRecordArray:record];
                
                [ApiUtillity dissmissSVProgressHUDViewWithSuccess:self.view WithMessage:@"Record updated"];
                
//                WeatherMainVC *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"WeatherMainVC"];
//                [self.navigationController pushViewController:vc animated:YES];
                
                [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
{
    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.img_Upload;
    popPresenter.sourceRect = self.img_Upload.frame;
    [self presentViewController:actionSheet animated:YES completion:nil];

    //-------------
//    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Upload Image"
//                                                             delegate:self
//                                                    cancelButtonTitle:@"Cancel"
//                                               destructiveButtonTitle:nil
//                                                otherButtonTitles:@"Gallery",@"Camera", nil];
//    
//    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
//        [actionSheet showFromRect:self.view.bounds inView:self.img_Upload animated:true];
//    }
//    else {
//        [actionSheet showInView:self.view];
//    }
    
}

-(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.img_Upload.frame inView:self.img_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.img_Upload.image = chosenImage;
    
    imageData = [self encodeToBase64String:_img_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];
}


#pragma 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];
    }
}


@end
