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

#import "AccidentsMainVC.h"
#import "cellAccidentVC.h"
#import "AccidentsVC.h"
#import "AFNetworking.h"
#import "ApiUtillity.h"
#import "KIImagePager.h"


@interface AccidentsMainVC ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UITextViewDelegate>{
    NSInteger SelectedProject;
    NSInteger SelectedJob;
    
    NSMutableArray *ProjectArray;
    NSMutableArray *UserDataArray;
    NSMutableArray *JobArray;
    
    NSUInteger tableviewRowCount;
    
    NSMutableArray *WitnessNameArray;
    NSMutableArray *WitnessMobileArray;
    NSMutableArray *WitnessDescArray;
    NSMutableArray *ImagesDisplayDataArray;

    
    
    IBOutlet KIImagePager *_imagePager;

    
}

@end

@implementation AccidentsMainVC
@synthesize delegate;

#pragma mark- ViewDidload
- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (_EditedsplitNameArray.count != 0) {
        tableviewRowCount = _EditedsplitNameArray.count;
    }
    else{
        tableviewRowCount = 3;
    }
    
    //For Piker
//    SelectedProject = 0;
//    SelectedJob = 0;
    
    JobArray = [[NSMutableArray alloc]init];
    UserDataArray = [[NSMutableArray alloc]init];
    ProjectArray = [[NSMutableArray alloc]init];
    
    WitnessNameArray = [[NSMutableArray alloc]init];
    WitnessMobileArray = [[NSMutableArray alloc]init];
    WitnessDescArray = [[NSMutableArray alloc]init];
    ImagesDisplayDataArray=[[NSMutableArray alloc]init];

    
    
    if ([_isEdited  isEqual: @"YES"]) {
        int i;
        for (i = 0; i < _EditedsplitNameArray.count; i++) {
            [WitnessNameArray addObject:[_EditedsplitNameArray objectAtIndex:i]];
            [WitnessMobileArray addObject:[_EditedsplitPhoneArray objectAtIndex:i]];
            
            if ([[_EditedsplitDescArray objectAtIndex:i]  isEqual: [NSNull null]]) {
                [WitnessDescArray addObject:@""];
            }
            else{
                [WitnessDescArray addObject:[_EditedsplitDescArray objectAtIndex:i]];
            }
        }
    }
}

-(void)viewWillAppear:(BOOL)animated{
    SelectedProject = [ApiUtillity getProjectNumber];
    SelectedJob = [ApiUtillity getJobNumber];

//    [self GetMainData];
    [self getUserDefaultData];
}

-(void)viewDidDisappear:(BOOL)animated{
    
}

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


#pragma mark- ButtonAction
- (IBAction)btn_bar_Back:(id)sender
{
    [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;
                                           
                                           [_btn_Project setTitle:[NSString stringWithFormat:@"%@", selectedValue] forState:UIControlStateNormal];
                                           //Set JOb Title
//                                           JobArray = [[ProjectArray objectAtIndex:selectedIndex]valueForKey:@"jobs"];
//                                           [_btn_Job 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_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_Add:(id)sender {
    tableviewRowCount = tableviewRowCount + 1;
    [_tableview_Witness reloadData];
}


- (IBAction)btn_Handler_Save:(id)sender {
    BOOL SaveFlag = 0;
    int i;
    for (i = 0; i < WitnessNameArray.count; i++) {
        NSString *Name,*Number,*Desc;
        if ((Name = [WitnessNameArray objectAtIndex:i]) && (Number = [WitnessMobileArray objectAtIndex:i]) && (Desc = [WitnessDescArray objectAtIndex:i])) {
            if ([Desc isEqualToString:@"Description"]) {
                [WitnessDescArray replaceObjectAtIndex:i withObject:@""];
            }
            
            if ([Name  isEqual: @""] && [Number  isEqual: @""]) {
                [WitnessNameArray removeObjectAtIndex:i];
                [WitnessMobileArray removeObjectAtIndex:i];
                [WitnessDescArray removeObjectAtIndex:i];
                i = i-1;
            }
            if ([Name  isEqual: @""] && ![Number  isEqual: @""]) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Fill Name" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
                SaveFlag = 1;
            }
        }
    }
    
    if (SaveFlag == 0) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(WittnessNameArray:WittnessMobileArray:WittnessDescArray:)]) {
            [self.delegate WittnessNameArray:WitnessNameArray WittnessMobileArray:WitnessMobileArray WittnessDescArray:WitnessDescArray];
            [self.navigationController popViewControllerAnimated:true];
        }
    }
    
//    NSLog(@"NameArray :-%@ AND MobileArray :-%@",WitnessNameArray,WitnessMobileArray);
}


#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"];
                    
                    //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];
                                NSLog(@"TempjobID :--- %d",TempjobID);
                        
                        
                        int i;
                        for (i=0; i<ProjectArray.count; i++) {
                            NSString *proID,*jobID;
                                    NSLog(@"Job id :--- %@",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];
//                                    }
//                                }
                            }
                        }
                    }
                }
            }
        }
        [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"];
//    JobArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"SubArray"];
    
    //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];
        NSLog(@"Tempjobid:-- %d",TempjobID);


        
        int i;
        for (i=0; i<ProjectArray.count; i++) {
            NSString *proID,*jobID;
                    NSLog(@"Job id :--- %@",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];
//                    }
//                }
            }
        }
    }
}




#pragma mark- UITextField Methode
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    CGRect rect = textField.frame;
    CGFloat y = rect.origin.y;
    
    if (y == 1) {
        NSUInteger tag = textField.tag;
        NSString *witnessMobile = [[NSString alloc]init];
        
        witnessMobile = [textField.text stringByReplacingCharactersInRange:range withString:string];
        NSLog(@"%@",witnessMobile);
        if (![witnessMobile  isEqual: @""]) {
            [WitnessMobileArray replaceObjectAtIndex:tag withObject:witnessMobile];
            NSLog(@"MobileArray :-%@",WitnessMobileArray);
            return true;
        }
        [WitnessMobileArray replaceObjectAtIndex:tag withObject:@""];
        NSLog(@"MobileArray :-%@",WitnessMobileArray);
    }
    else if (y == 0){
        NSUInteger tag = textField.tag;
        NSString *witnessName = [[NSString alloc]init];
        
        witnessName = [textField.text stringByReplacingCharactersInRange:range withString:string];
        NSLog(@"%@",witnessName);
        if (![witnessName  isEqual: @""]) {
            [WitnessNameArray replaceObjectAtIndex:tag withObject:witnessName];
            NSLog(@"NameArray :-%@",WitnessNameArray);
            return true;
        }
        [WitnessNameArray replaceObjectAtIndex:tag withObject:@""];
        NSLog(@"NameArray :-%@",WitnessNameArray);
    }
    return true;
}


#pragma mark- UITextView Methode
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    NSUInteger tag = textView.tag;
    if (![text  isEqual: @""]) {
        NSString *witnessDesc = [[NSString alloc]init];
        witnessDesc = [textView.text stringByReplacingCharactersInRange:range withString:text];
        
        NSLog(@"%@",witnessDesc);
        if (![witnessDesc  isEqual: @""]) {
            [WitnessDescArray replaceObjectAtIndex:tag withObject:witnessDesc];
            NSLog(@"DescArray :-%@",WitnessDescArray);
            return true;
        }
        [WitnessDescArray replaceObjectAtIndex:tag withObject:@""];
        NSLog(@"DescArray :-%@",WitnessDescArray);
    }
    else{
        if (![textView.text isEqualToString:@""]) {
            NSString *witnessDesc = [[NSString alloc]init];
            witnessDesc = [textView.text substringToIndex:[textView.text length] - 1];
            
            NSLog(@"%@",witnessDesc);
            if (![witnessDesc  isEqual: @""]) {
                [WitnessDescArray replaceObjectAtIndex:tag withObject:witnessDesc];
                NSLog(@"DescArray :-%@",WitnessDescArray);
                return true;
            }
            [WitnessDescArray replaceObjectAtIndex:tag withObject:@""];
            NSLog(@"DescArray :-%@",WitnessDescArray);
        }
    }
    
    return true;
}

/*
- (void)textViewDidChange:(UITextView *)textView {
    NSUInteger tag = textView.tag;
    if (![textView.text  isEqual: @""]) {
        NSString *witnessDesc = [[NSString alloc]init];
        witnessDesc = textView.text;
        
        NSLog(@"%@",witnessDesc);
        if (![witnessDesc  isEqual: @""]) {
            [WitnessDescArray replaceObjectAtIndex:tag withObject:witnessDesc];
            NSLog(@"DescArray :-%@",WitnessDescArray);
            return ;
        }
        [WitnessDescArray replaceObjectAtIndex:tag withObject:@""];
        NSLog(@"DescArray :-%@",WitnessDescArray);
    }
 }*/;

-(void)textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@"Description"]) {
        NSUInteger tag = textView.tag;
        [WitnessDescArray replaceObjectAtIndex:tag withObject:@""];
        textView.text = @"";
    }
    textView.textColor = [UIColor blackColor];
}


#pragma mark- Tableview Methode
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return tableviewRowCount;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //cellWeather
    static NSString *Indentifier = @"cellAccidentVC";
    cellAccidentVC *cell = [_tableview_Witness dequeueReusableCellWithIdentifier:Indentifier];
    if (cell == nil) {
        cell = [[cellAccidentVC alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Indentifier];
    }
    
    //For Wittness Mobile
    cell.txt_PhoneNumber.tag = indexPath.row;
//    [cell.txt_PhoneNumber addTarget:self action:@selector(textField:shouldChangeCharactersInRange:replacementString:) forControlEvents:UIControlEventEditingChanged];
    cell.txt_PhoneNumber.delegate = self;
    if (WitnessMobileArray.count == indexPath.row) {
        [WitnessMobileArray insertObject:@"" atIndex:indexPath.row];
    }
    if (cell.txt_PhoneNumber.tag == indexPath.row) {
        cell.txt_PhoneNumber.text = [WitnessMobileArray objectAtIndex:indexPath.row];
    }
    
    //For Wittness Name
    cell.txt_Name.tag = indexPath.row;
    cell.txt_Name.delegate = self;
    if (WitnessNameArray.count == indexPath.row) {
        [WitnessNameArray insertObject:@"" atIndex:indexPath.row];
    }
    if (cell.txt_Name.tag == indexPath.row) {
        cell.txt_Name.text = [WitnessNameArray objectAtIndex:indexPath.row];
    }
    
    //For Wittness Desc
    cell.textView_Witness.tag = indexPath.row;
    cell.textView_Witness.delegate = self;
    cell.textView_Witness.text = @"Description";
    if (WitnessDescArray.count == indexPath.row) {
        [WitnessDescArray insertObject:@"Description" atIndex:indexPath.row];
    }
    if (cell.textView_Witness.tag == indexPath.row) {
        cell.textView_Witness.text = [WitnessDescArray objectAtIndex:indexPath.row];
    }
    
    return cell;
}

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

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        tableviewRowCount = tableviewRowCount - 1;
        [WitnessNameArray removeObjectAtIndex:indexPath.row];
        [WitnessMobileArray removeObjectAtIndex:indexPath.row];
        
        [_tableview_Witness beginUpdates];
        [_tableview_Witness deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
        [_tableview_Witness endUpdates];
        
        NSLog(@"NameArray :-%@",WitnessNameArray);
        NSLog(@"MobileArray :-%@",WitnessMobileArray);
//        [_tableview_Witness reloadData];
    }
}


@end
