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

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

@interface VisitorsMainVC ()<VisitorDelegate>{
    NSInteger SelectedProject;
    NSInteger SelectedJob;
    NSInteger SelectedSub;
    NSInteger SelectedEmployee;
    
    NSMutableArray *ProjectArray;
    NSMutableArray *EmployeeArray;
    NSMutableArray *SubArray;
    NSMutableArray *UserDataArray;
    NSMutableArray *JobArray;
    
    NSMutableArray *getVisitorData;
    NSMutableArray *EditedArray;
    
    NSString *DeleteRecordID;
    NSUInteger deleteIndex;
    NSIndexPath *deleteTableIndex;

}

@end

@implementation VisitorsMainVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    JobArray = [[NSMutableArray alloc]init];
    UserDataArray = [[NSMutableArray alloc]init];
    ProjectArray = [[NSMutableArray alloc]init];
    EmployeeArray = [[NSMutableArray alloc]init];
    SubArray = [[NSMutableArray alloc]init];
    
    getVisitorData = [[NSMutableArray alloc]init];
    EditedArray = [[NSMutableArray alloc]init];
    
}

-(void)viewWillAppear:(BOOL)animated{
    SelectedProject = [ApiUtillity getProjectNumber];
    SelectedJob = [ApiUtillity getJobNumber];
    
    _view_PopUp.hidden = true;
    
    //    [self getVisitorData];
    [self getUserDefaultData];
    [self getVisitorData];
}

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


#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"];
                                           
                                           [self getVisitorData];
                                       }
                                     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"];
                                           
                                           [self getVisitorData];
                                       }
                                     cancelBlock:^(ActionSheetStringPicker *picker) {
                                         NSLog(@"Block Picker Canceled");
                                     }
                                          origin:sender];
}
- (IBAction)btn_Handler_Add:(id)sender {
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        VisitorsVC *VC = (VisitorsVC *)[storyboard instantiateViewControllerWithIdentifier:@"VisitorsVC"];
        VC.delegate = self;
        [self.navigationController pushViewController:VC animated:true];
    }
    else{
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStory_iPad" bundle:nil];
        VisitorsVC *VC = (VisitorsVC *)[storyboard instantiateViewControllerWithIdentifier:@"VisitorsVC"];
        VC.delegate = self;
        [self.navigationController pushViewController:VC animated:true];
    }
}

- (IBAction)btn_Handler_Save:(id)sender {
    
}

- (IBAction)btn_Handler_Edit:(id)sender {
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        VisitorsVC *VC = (VisitorsVC *)[storyboard instantiateViewControllerWithIdentifier:@"VisitorsVC"];
        VC.delegate = self;
        VC.isEdited = [[NSString alloc]init];
        VC.isEdited = @"YES";
        VC.EditedArray = [[NSMutableArray alloc]init];
        VC.EditedArray = EditedArray;
        [self.navigationController pushViewController:VC animated:true];
    }
    else{
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStory_iPad" bundle:nil];
        VisitorsVC *VC = (VisitorsVC *)[storyboard instantiateViewControllerWithIdentifier:@"VisitorsVC"];
        VC.delegate = self;
        VC.isEdited = [[NSString alloc]init];
        VC.isEdited = @"YES";
        VC.EditedArray = [[NSMutableArray alloc]init];
        VC.EditedArray = EditedArray;
        [self.navigationController pushViewController:VC animated:true];
    }
}

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


#pragma mark- All Methode
-(void)getRecordArray:(NSMutableArray *)recordArray{
    [getVisitorData removeAllObjects];
    //    getVisitorData = recordArray;
    for (NSMutableDictionary *Dic in recordArray) {
        [getVisitorData addObject:Dic];
    }
    
    [_tableview_Desc reloadData];
}

- (void) getUserDefaultData{
    ProjectArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"ProjectArray"];
    SubArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"SubArray"];
    EmployeeArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"EmployeeArray"];
    
    
    //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);
        
        
        //FOR Project & Job...
        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];
                //                    }
                //                }
            }
        }
    }
    
}

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

    
    NSDictionary *params = @{@"date":Date,@"uid":UID,@"type":Type,@"project_id":ProID};
    
    [manager POST:@"http://p4bdesigns.com/Gilliatteweb/app/api3/record_get.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@",responseObject);
        if (responseObject != nil) {
            NSString *Suceess;
            if ((Suceess = [responseObject valueForKey:@"success"])) {
                if ([Suceess  isEqual: @"ok"]) {
                    [getVisitorData removeAllObjects];
                    
                    NSMutableArray *dataArray;
                    dataArray = [responseObject valueForKey:@"records"];
                    for (NSMutableDictionary *Dic in dataArray) {
                        [getVisitorData addObject:Dic];
                    }
                    
                    [_tableview_Desc reloadData];
                }
            }
        }
        [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) DeleteVisitorData{
    [ApiUtillity setSVProgressHUDView:self.view];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager.requestSerializer setTimeoutInterval:150.0];

    
    NSDictionary *params = @{@"id":DeleteRecordID};
    
    [manager POST:@"http://p4bdesigns.com/Gilliatteweb/app/api3/record_delete.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject != nil) {
            NSString *Suceess;
            if ((Suceess = [responseObject valueForKey:@"success"])) {
                if ([Suceess  isEqual: @"Deleted"]) {
                    //                    [self getVisitorData];
                    [getVisitorData removeObjectAtIndex:deleteIndex];
                    [_tableview_Desc deleteRowsAtIndexPaths:@[deleteTableIndex] withRowAnimation:UITableViewRowAnimationFade];
                    [_tableview_Desc reloadData];
                }
            }
        }
        [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) showPopUp:(NSUInteger)number{
    _view_PopUp.hidden = false;
    
    _indicator_PopUp.hidden = false;
    [_indicator_PopUp startAnimating];
    NSString *img = [[getVisitorData valueForKey:@"img"]objectAtIndex:number];
    [_imageview_PopUp sd_setImageWithURL:[NSURL URLWithString:img] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        [_indicator_PopUp stopAnimating];
        _indicator_PopUp.hidden = true;
    }];
    _lbl_DateTime_PopUp.text = [[getVisitorData valueForKey:@"date"]objectAtIndex:number];
     _lbl_NamePopUp.text = [[getVisitorData valueForKey:@"name"]objectAtIndex:number];
    _lbl_Desc_PopUp.text = [[getVisitorData valueForKey:@"description"]objectAtIndex:number];
}


#pragma mark- Tableview Methode
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (getVisitorData.count != 0) {
        self.tableview_Desc.backgroundView = nil;
        
        return getVisitorData.count;
    }
    else{
        UILabel *noDataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.tableview_Desc.bounds.size.width, self.tableview_Desc.bounds.size.height)];
        noDataLabel.text             = @"No Data Found.";
        noDataLabel.textColor        = [UIColor blackColor];
        noDataLabel.textAlignment    = NSTextAlignmentCenter;
        self.tableview_Desc.backgroundView = noDataLabel;
        self.tableview_Desc.separatorStyle = UITableViewCellSeparatorStyleNone;
        return 0;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *Indentifier = @"cellVisitor";
    UITableViewCell *cell = [_tableview_Desc dequeueReusableCellWithIdentifier:Indentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Indentifier];
    }
    
    UIActivityIndicatorView *indicator = [cell viewWithTag:4];
    [indicator startAnimating];
    UIImageView *WorkPerformImage = [cell viewWithTag:1];
    NSString *img = [[getVisitorData valueForKey:@"img"]objectAtIndex:indexPath.row];
    [WorkPerformImage sd_setImageWithURL:[NSURL URLWithString:img] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        [indicator stopAnimating];
    }];
    
    UILabel *Date = [cell viewWithTag:2];
    Date.text = [[getVisitorData valueForKey:@"date"]objectAtIndex:indexPath.row];
    
    UILabel *subName = [cell viewWithTag:5];
    subName.text = [[getVisitorData valueForKey:@"name"]objectAtIndex:indexPath.row];
    
    UILabel *Desc = [cell viewWithTag:3];
    Desc.text = [[getVisitorData valueForKey:@"description"]objectAtIndex:indexPath.row];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self showPopUp:indexPath.row];
    EditedArray = [getVisitorData objectAtIndex:indexPath.row];
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        deleteIndex = indexPath.row;
        deleteTableIndex = indexPath;
        
        DeleteRecordID = [[getVisitorData valueForKey:@"id"] objectAtIndex:indexPath.row];
        [self DeleteVisitorData];
    }
}

@end