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

#import "EnterDailyReportMainVC.h"
#import "DSLCalendarView.h"
#import "ActionSheetPicker.h"
#import "ApiUtillity.h"
#import "GilliatteVC.h"
#import "SlideMenuController.h"
#import "SideMenuVC.h"
#import "AFNetworking.h"

@interface EnterDailyReportMainVC (){
    NSInteger SelectedProject;
    NSInteger SelectedJob;
    NSString *SelectedDate;
    
    NSMutableArray *ProjectArray;
    NSMutableArray *EmployeeArray;
    NSMutableArray *SubArray;
    NSMutableArray *UserDataArray;
    NSMutableArray *JobArray;
}

@end

@implementation EnterDailyReportMainVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *date;
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    date = [dateFormatter stringFromDate:[NSDate date]];
    [[NSUserDefaults standardUserDefaults] setObject:date forKey:@"SELECTED_DATE"];
    
    
    SelectedProject = 0;
    SelectedJob = 0;
    
    JobArray = [[NSMutableArray alloc]init];
    UserDataArray = [[NSMutableArray alloc]init];
    ProjectArray = [[NSMutableArray alloc]init];
    EmployeeArray = [[NSMutableArray alloc]init];
    SubArray = [[NSMutableArray alloc]init];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [self GetMainData];
    [[self navigationController] setNavigationBarHidden:NO animated:YES];
    [ApiUtillity setTransculantNavigation:self.navigationController];
}


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


#pragma mark- ButtonAction
- (IBAction)btn_bar_SideMenu:(id)sender {
    SlideMenuController *slideMenuController = self.slideMenuController;
    if (slideMenuController != nil) {
        [self.slideMenuController openLeft];
    }
}

- (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;
                                           [_btn_SelectProject setTitle:[NSString stringWithFormat:@"%@", selectedValue] forState:UIControlStateNormal];
                                           //Set JOb Title
//                                           JobArray = [[ProjectArray objectAtIndex:selectedIndex]valueForKey:@"jobs"];
//                                           [_btn_SelectJob 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_SelectJob:(id)sender {
    NSArray *Job = [[NSArray alloc]init];
    NSMutableArray *JobSubArray = [[NSMutableArray alloc]init];
    JobArray = [[ProjectArray objectAtIndex:SelectedProject]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_SelectJob 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_Proceed:(id)sender {
    NSLog(@"%@",SelectedDate);
    
    NSString *Date;
    if (!(Date = [[NSUserDefaults standardUserDefaults] objectForKey:@"SELECTED_DATE"]))
    {
        UIAlertView *alert = [[UIAlertView alloc]init];
        alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Select Date." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        GilliatteVC *VC = (GilliatteVC *)[storyboard instantiateViewControllerWithIdentifier:@"GilliatteVC"];
        [self.navigationController pushViewController:VC animated:true];
    }
    else{
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStory_iPad" bundle:nil];
        GilliatteVC *VC = (GilliatteVC *)[storyboard instantiateViewControllerWithIdentifier:@"GilliatteVC"];
        [self.navigationController pushViewController:VC animated:true];
    }
    
    
}


#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"];
                    
                    //StoreDataOfSelection
                    [[NSUserDefaults standardUserDefaults] setObject:ProjectArray forKey:@"ProjectArray"];
                    [[NSUserDefaults standardUserDefaults] setObject:EmployeeArray forKey:@"EmployeeArray"];
                    [[NSUserDefaults standardUserDefaults] setObject:SubArray forKey:@"SubArray"];
                    
                    
                    //Set Project Title
                    [_btn_SelectProject setTitle:[[ProjectArray objectAtIndex:0]valueForKey:@"project_name"] forState:UIControlStateNormal];
                    //Set JOb Title
                    JobArray = [[ProjectArray objectAtIndex:0]valueForKey:@"jobs"];
                    [_btn_SelectJob setTitle:[[JobArray objectAtIndex:0] valueForKey:@"job_title"] forState:UIControlStateNormal];
                    
                    //SET USER_DEFAULT
                    NSString *ProjectId,*JobId,*employeeId,*subsId;
                    ProjectId = [[NSString alloc]init];
                    JobId = [[NSString alloc]init];
                    employeeId = [[NSString alloc]init];
                    subsId = [[NSString alloc]init];
                    
                    ProjectId = [[ProjectArray objectAtIndex:0]valueForKey:@"project_id"];
//                    JobId = [[JobArray objectAtIndex:0] valueForKey:@"job_id"];
                    employeeId = [[EmployeeArray objectAtIndex:0] valueForKey:@"id"];
                    subsId = [[SubArray objectAtIndex:0]valueForKey:@"id"];
                    [[NSUserDefaults standardUserDefaults] setObject:ProjectId forKey:@"PROJECT_ID"];
//                    [[NSUserDefaults standardUserDefaults] setObject:JobId forKey:@"JOB_ID"];
                    [[NSUserDefaults standardUserDefaults] setObject:subsId forKey:@"SUB_ID"];
                    [[NSUserDefaults standardUserDefaults] setObject:employeeId forKey:@"EMPLOYEE_ID"];
                }
            }
        }
        [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];
        
    }];
    
}


#pragma mark FSCalendarDelegate

- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date
{
    NSLog(@"select date is :-%@",[calendar stringFromDate:date format:@"MM/dd/yyyy"]);
    
    SelectedDate = [calendar stringFromDate:date format:@"MM/dd/yyyy"];
    [[NSUserDefaults standardUserDefaults] setObject:SelectedDate forKey:@"SELECTED_DATE"];
}

- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar
{
    NSLog(@"change to page to :-%@",[calendar stringFromDate:calendar.currentPage format:@"MMMM yyyy"]);
}

@end
