//
//  IncidentLog.m
//  DUREX Vendor Control
//
//  Created by Imanol Barba on 10/8/14.
//  Copyright (c) 2014 Emmoco. All rights reserved.
//

#import "IncidentLog.h"

@implementation IncidentLog

- (id) init
{
    [self setIncidents:[[NSMutableArray alloc] init]];
    return self;
}

- (void) setResponseValue:(NSString *)response
{
    [self setResponse: response];
    [self parseResponse];
}

- (void) parseResponse
{
    NSInteger currentIncident = 0;
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSCalendarUnit units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
    NSDateComponents *incidentDate = [[NSDateComponents alloc] init];
    NSInteger currentYear = [[calendar components:units fromDate:[NSDate date]] year];
    currentYear = (currentYear/100)*100;
    while(![[[self response] substringWithRange:NSMakeRange((currentIncident*INCIDENT_STRING_LENGTH), 4)] isEqualToString:@"P3P3"])
    {
        Incident *incident = [[Incident alloc] init];
        [incidentDate setYear:(currentYear + [[[self response] substringWithRange:NSMakeRange(2 + currentIncident*INCIDENT_STRING_LENGTH, 2)] intValue])];
        [incidentDate setMonth:[[[self response] substringWithRange:NSMakeRange(4 + currentIncident*INCIDENT_STRING_LENGTH, 2)] intValue]];
        [incidentDate setDay:[[[self response] substringWithRange:NSMakeRange(6 + currentIncident*INCIDENT_STRING_LENGTH, 2)] intValue]];
        [incidentDate setHour:[[[self response] substringWithRange:NSMakeRange(8 + currentIncident*INCIDENT_STRING_LENGTH, 2)] intValue]];
        [incidentDate setMinute:[[[self response] substringWithRange:NSMakeRange(10 + currentIncident*INCIDENT_STRING_LENGTH, 2)] intValue]];
        [incidentDate setMinute:[[[self response] substringWithRange:NSMakeRange(12 + currentIncident*INCIDENT_STRING_LENGTH, 2)] intValue]];
        [incident setIncidentTime:[calendar dateFromComponents:incidentDate]];
        NSLog(@"date: %@",[calendar dateFromComponents:incidentDate]);
        [incident setErrorCode:[[self response] substringWithRange:NSMakeRange(14 + currentIncident*INCIDENT_STRING_LENGTH, 2)]];
        NSLog(@"errorCode: %@",[incident errorCode]);
        [incident setErrorValue:[[self response] substringWithRange:NSMakeRange(16 + currentIncident*INCIDENT_STRING_LENGTH, 4)]];
        NSLog(@"errorValue: %@",[incident errorValue]);
        [[self incidents] insertObject:incident atIndex:currentIncident];
        currentIncident++;
    }
    NSLog(@"%@",[self incidents]);
}

@end

