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

#import "GilliatteVC.h"
#import "WeatherMainVC.h"
#import "WeatherVC.h"
#import "WorkFlowVC.h"
#import "ActionSheetPicker.h"
#import "WorkPerformedMainVC.h"
#import "WorkPerformedVC.h"
#import "AccidentsVC.h"
#import "AccidentsListVC.h"
#import "SubDeliveryVC.h"
#import "SubDeliveryMainVC.h"
#import "VisitorsVC.h"
#import "SafetyVC.h"
#import "SafetyMainVC.h"
#import "AFNetworking.h"
#import "ApiUtillity.h"
#import "VisitorsMainVC.h"
#import "EnterDailyReportMainVC.h"
#import "EnterDailyReportVC.h"

@interface GilliatteVC (){
    NSArray *imageArray;
    NSArray *nameArray;
    
    NSInteger SelectedProject;
    NSInteger SelectedJob;
    
    NSMutableArray *ProjectArray;
    NSMutableArray *EmployeeArray;
    NSMutableArray *SubArray;
    NSMutableArray *UserDataArray;
    NSMutableArray *JobArray;
}

@end

@implementation GilliatteVC

#pragma mark- ViewDidload
- (void)viewDidLoad {
    [super viewDidLoad];
//    SelectedProject = 0;
//    SelectedJob = 0;
    
    JobArray = [[NSMutableArray alloc]init];
    UserDataArray = [[NSMutableArray alloc]init];
    ProjectArray = [[NSMutableArray alloc]init];
    EmployeeArray = [[NSMutableArray alloc]init];
    SubArray = [[NSMutableArray alloc]init];
    
    imageArray = [[NSArray alloc]initWithObjects:@"G_Weather Icon.png",@"G_Work Performed Icon.png",@"G_Accidents Icon.png",@"G_Sub. Delivery Icon.png",@"G_Visitors.png",@"G_Safety.png",@"G_Workflow.png",nil];
    nameArray = [[NSArray alloc]initWithObjects:@"Weather",@"Work Performed",@"Incidents",@"Deliveries",@"Visitors",@"Safety",@"Work Force",nil];
}

-(void)viewWillAppear:(BOOL)animated{
    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"SUB_ID"];
    
    SelectedProject = [ApiUtillity getProjectNumber];
    SelectedJob = [ApiUtillity getJobNumber];
    
//    [self GetMainData];
    [self getUserDefaultData];
}

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

#pragma mark- All Methode


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

- (IBAction)btn_Handler_ProjectB:(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_Job2:(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];
}


#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;
                    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"];
//    JobArray = [[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 :--- %@",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_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];
//                    }
//                }
            }
        }
    }
}


#pragma mark- Tableview Methode
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return nameArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //MenuCell
    static NSString *Indentifier = @"cellGilliate";
    UITableViewCell *cell = [_tableview_Gilliatte dequeueReusableCellWithIdentifier:Indentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Indentifier];
    }
    
    UIImageView *imageView = [cell viewWithTag:1];
    imageView.image = [UIImage imageNamed:imageArray[indexPath.row]];
    
    UILabel *label = [cell viewWithTag:2];
    label.text = nameArray[indexPath.row];
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%ld",(long)indexPath.row);
    if (indexPath.row == 0) {
//        Weather
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            WeatherMainVC *VC = (WeatherMainVC *)[storyboard instantiateViewControllerWithIdentifier:@"WeatherMainVC"];
            [self.navigationController pushViewController:VC animated:true];
        }
        else{
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStory_iPad" bundle:nil];
            WeatherMainVC *VC = (WeatherMainVC *)[storyboard instantiateViewControllerWithIdentifier:@"WeatherMainVC"];
            [self.navigationController pushViewController:VC animated:true];
        }
    }
    else if (indexPath.row == 1){
//        Work Performed
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            WorkPerformedMainVC *VC = (WorkPerformedMainVC *)[storyboard instantiateViewControllerWithIdentifier:@"WorkPerformedMainVC"];
            [self.navigationController pushViewController:VC animated:true];
        }
        else{
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStory_iPad" bundle:nil];
            WorkPerformedMainVC *VC = (WorkPerformedMainVC *)[storyboard instantiateViewControllerWithIdentifier:@"WorkPerformedMainVC"];
            [self.navigationController pushViewController:VC animated:true];
        }
        
    }
    else if (indexPath.row == 2){
//        Accidents
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            AccidentsListVC *VC = (AccidentsListVC *)[storyboard instantiateViewControllerWithIdentifier:@"AccidentsListVC"];
            
            [self.navigationController pushViewController:VC animated:true];
            
        }
        else{
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStory_iPad" bundle:nil];
            AccidentsListVC *VC = (AccidentsListVC *)[storyboard instantiateViewControllerWithIdentifier:@"AccidentsListVC"];
            
            [self.navigationController pushViewController:VC animated:true];
        }
        
    }
    else if (indexPath.row == 3){
//        Sub. Delivery
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            SubDeliveryMainVC *VC = (SubDeliveryMainVC *)[storyboard instantiateViewControllerWithIdentifier:@"SubDeliveryMainVC"];
            [self.navigationController pushViewController:VC animated:true];
        }
        else{
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStory_iPad" bundle:nil];
            SubDeliveryMainVC *VC = (SubDeliveryMainVC *)[storyboard instantiateViewControllerWithIdentifier:@"SubDeliveryMainVC"];
            [self.navigationController pushViewController:VC animated:true];
        }
        
    }
    else if (indexPath.row == 4){
//        Visitors
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            VisitorsMainVC *VC = (VisitorsMainVC *)[storyboard instantiateViewControllerWithIdentifier:@"VisitorsMainVC"];
            [self.navigationController pushViewController:VC animated:true];
        }
        else{
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStory_iPad" bundle:nil];
            VisitorsMainVC *VC = (VisitorsMainVC *)[storyboard instantiateViewControllerWithIdentifier:@"VisitorsMainVC"];
            [self.navigationController pushViewController:VC animated:true];
        }
        
    }
    else if (indexPath.row == 5){
//        Safety
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            SafetyMainVC *VC = (SafetyMainVC *)[storyboard instantiateViewControllerWithIdentifier:@"SafetyMainVC"];
            [self.navigationController pushViewController:VC animated:true];
        }
        else{
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStory_iPad" bundle:nil];
            SafetyMainVC *VC = (SafetyMainVC *)[storyboard instantiateViewControllerWithIdentifier:@"SafetyMainVC"];
            [self.navigationController pushViewController:VC animated:true];
        }
        
    }
    else if (indexPath.row == 6){
//        Workflow
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            WorkFlowVC *VC = (WorkFlowVC *)[storyboard instantiateViewControllerWithIdentifier:@"WorkFlowVC"];
            [self.navigationController pushViewController:VC animated:true];
        }
        else{
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStory_iPad" bundle:nil];
            WorkFlowVC *VC = (WorkFlowVC *)[storyboard instantiateViewControllerWithIdentifier:@"WorkFlowVC"];
            [self.navigationController pushViewController:VC animated:true];
        }
        
    }
}
@end
