/* GrandPerspective, Version 3.4.1 
 *   A utility for Mac OS X that graphically shows disk usage. 
 * Copyright (C) 2005-2022, Erwin Bonsma 
 * 
 * This program is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU General Public License as published by the Free 
 * Software Foundation; either version 2 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for 
 * more details. 
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA. 
 */

#import "ReadProgressTracker.h"

static const int READ_BUFFER_SIZE = 16384;


@implementation ReadProgressTracker

- (instancetype) init {
  if (self = [super init]) {
    totalLines = 0;
    processedLines = 0;
  }

  return self;
}

- (void) startingTaskOnInputData:(NSData *)inputData {
  // Determine the total number of lines in the input data
  char  buffer[READ_BUFFER_SIZE];

  // For better performance on large input data, read only complete blocks in the main loop.
  NSUInteger  numBlocks = inputData.length / READ_BUFFER_SIZE;
  NSUInteger  maxpos = numBlocks * READ_BUFFER_SIZE;
  NSUInteger  pos = 0;
  while (pos < maxpos) {
    [inputData getBytes: (void *)buffer range: NSMakeRange(pos, READ_BUFFER_SIZE)];
    int  i = READ_BUFFER_SIZE;
    while (i--) {
      // Note: Even though input is in UTF-8, which can contain multi-byte
      // characters, the nature of the encoding ensures that each byte
      // corresponding to an ASCII character is indeed one.
      if (buffer[i]=='\n') {
        totalLines++;
      }
    }

    pos += READ_BUFFER_SIZE;
  }

  // Read the last, partially filled, block, if any.
  NSUInteger  i = inputData.length - pos;
  if (i > 0) {
    [inputData getBytes: (void *)buffer range: NSMakeRange(pos, i)];
    while (i--) {
      if (buffer[i]=='\n') {
        totalLines++;
      }
    }
  }

  NSLog(@"totalLines = %ld", (long)totalLines);
}


- (void) processingFolder:(DirectoryItem *)dirItem
           processedLines:(NSInteger)numProcessed {
  [mutex lock];

  // For efficiency, call internal method that assumes mutex has been locked.
  [self _processingFolder: dirItem];

  NSAssert(numProcessed <= totalLines,
           @"More lines processed than expected (%ld > %ld).",
           (long)numProcessed, (long)totalLines);
  processedLines = numProcessed;

  [mutex unlock];
}


- (float) estimatedProgress {
  if (totalLines == 0) {
    return 0;
  } else {
    return 100.0 * processedLines / totalLines;
  }
}

@end
