//
//  Export.m
//  DrivoMeter
//
//  Created by Triin Uudam on 4/17/12.
//  Copyright (c) 2012 Mobi Solutions OÜ. All rights reserved.
//

#import "Export.h"
#import "Database+Trips.h"
#import "Database+User.h"
#import "Trip.h"
#import "CHCSVWriter.h"
#import "User.h"
#import "SKPSMTPMessage.h"
#import "NSStream+SKPSMTPExtensions.h"
#import "NSData+Base64Additions.h"
#import "Constants.h"
#import "NSDate+Extensions.h"

@interface Export (Private)

- (double)totalDistanceForAllTrips:(NSArray *)trips;
- (double)totalDistanceForPrivateTrips:(NSArray *)trips;

@end
@implementation Export

@synthesize beginningDate = beginningDate_;
@synthesize endDate = endDate_;
@synthesize database = database_;
@synthesize delegate = delegate_;
@synthesize emailIsSent = emailIsSent_;

- (id)initFrom:(NSDate *)begin to:(NSDate *)end {
  self = [super init];
  
  if (self) {
    [self setBeginningDate:begin];
    [self setEndDate:end];
  }
  
  return self;
}

- (void)exportData {
  
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES); 
  NSString *documentsDir = [paths objectAtIndex:0];
  NSString *root = [documentsDir stringByAppendingPathComponent:@"trips.csv"];
  
  User *user = [database_ currentUser];
  
  CHCSVWriter *writer = [[CHCSVWriter alloc] initWithCSVFile:root atomic:YES];
  [writer setEncoding:NSUTF8StringEncoding];
  [writer writeLineOfFields:([user.company length] > 0 ? user.company : @""), @"", [NSString stringWithFormat:@"Registrikood: %@", ([user.businessRegisterCode length] > 0 ? user.businessRegisterCode : @"")], nil];  
  
  [writer writeLineOfFields:@"Auto registrinumber", ([user.carNumber length] > 0 ? user.carNumber : @""), @"", @"", nil];
  
  [writer writeLine];
  [writer writeLineOfFields:@"Kuupäev", @"Odomeetri", @"Odomeetri", @"Distants", @"Sõidu", nil];
  [writer writeLineOfFields:@"", @"algnäit",@"lõppnäit", @"km", @"eesmärk", nil];
  NSArray *trips = [database_ listTripsFrom:beginningDate_ to:endDate_];
  [writer writeLine];
  for (Trip *trip in trips) {
    [writer writeLineOfFields:[trip.beginDate stringFromDate], 
     [NSString stringWithFormat:@"%.1f", trip.beginStateValue], 
     [NSString stringWithFormat:@"%.1f", trip.endStateValue], 
     [NSString stringWithFormat:@"%.1f", trip.distanceValue], trip.purpose, (trip.isBusinessValue ? NSLocalizedString(@"business.trip", nil) : NSLocalizedString(@"private.trip", nil)), nil];
  }
  [writer writeLine];
  [writer writeLineOfFields:@"", @"", @"Kokku:", [NSString stringWithFormat:@"%.1f km", [self totalDistanceForAllTrips:trips]], nil];
  [writer writeLine];
  [writer writeLineOfFields:@"", @"", @"Erasõite:", [NSString stringWithFormat:@"%.1f km", [self totalDistanceForPrivateTrips:trips]], nil];
  [writer closeFile];
  
  SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
  testMsg.fromEmail = @"soidupaevik@gmail.com";
  testMsg.toEmail = user.email;
  testMsg.relayHost = @"smtp.gmail.com";
  testMsg.requiresAuth = YES;
  testMsg.login = @"soidupaevik";
  testMsg.pass = @"soidame123";
  testMsg.subject = @"Sõidupäeviku andmete eksport";
  testMsg.wantsSecure = YES;
  testMsg.delegate = self;
  
  NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:@"text/plain",kSKPSMTPPartContentTypeKey,
                             @"Andmete eksport",kSKPSMTPPartMessageKey,@"utf-8",kSKPSMTPPartContentTransferEncodingKey,nil];
  
  NSData *tripData = [NSData dataWithContentsOfFile:root];
  
  NSDictionary *tripsPart = [NSDictionary dictionaryWithObjectsAndKeys:@"text/csv;\r\n\tname=\"trips.csv\"",kSKPSMTPPartContentTypeKey,
                             @"attachment;\r\n\tfilename=\"trips.csv\"",kSKPSMTPPartContentDispositionKey,@"base64",kSKPSMTPPartContentTransferEncodingKey,@"text/csv;\r\n\tname=trips.csv;\r\n\tx-unix-mode=0666",kSKPSMTPPartContentTypeKey,
                             [tripData encodeWrappedBase64ForData],kSKPSMTPPartMessageKey,nil];
  
  testMsg.parts = [NSArray arrayWithObjects:plainPart,tripsPart,nil];
  
  [testMsg send];
  emailIsSent_ = NO;
}

- (void)messageSent:(SKPSMTPMessage *)message
{
  MSLog(@">>>>>> delegate - message sent");
  [self.delegate emailSent];
  emailIsSent_ = YES;
}

- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error
{  
  if (!emailIsSent_) {
    [self.delegate emailSendFail];
  }
  MSLog(@">>>>>> delegate - error(%d): %@", [error code], [error localizedDescription]);
}

- (double)totalDistanceForAllTrips:(NSArray *)trips {
  double totalDistance = 0.0f;
  for (Trip *trip in trips) {
    totalDistance += trip.distanceValue;
  }
  return totalDistance;
}

- (double)totalDistanceForPrivateTrips:(NSArray *)trips {
  double privateDist = 0.0f;
  for (Trip *trip in trips) {
    if (!trip.isBusinessValue) {
      privateDist += trip.distanceValue;
    }
  }
  return privateDist;
}
@end
