// Copyright 2014 The Chromium Authors. All rights reserved.

// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd

'use strict';

/**
 * Responds to a request to truncate the contents of a file.
 * @param {Object} options Input options.
 * @param {function} onSuccess Function to be called if the file was
 *     read successfully.
 * @param {function} onError Function to be called if an error occured while
 *     attempting to read the file.
 */
var onTruncateFileRequested = function(options, onSuccess, onError) {
  // Strip the leading slash, since not used internally.
  var path = options.filePath.substring(1);

  var readParameters = s3fs.parameters({
    Key: path
  });

  s3fs.s3.getObject(readParameters, function(error, data) {
    if (error) {
      // TODO(lavelle): add logic for returning more specific error codes.
      onError('FAILED');
    } else {
      var buffer = data.Body.toArrayBuffer();
      var truncated = buffer.slice(0, options.length);

      var writeParameters = s3fs.parameters({
        Key: path,
        Body: truncated,
        ContentLength: truncated.byteLength
      });

      s3fs.s3.putObject(writeParameters, function(error, data) {
        if (error) {
          onError('FAILED');
        } else {
          onSuccess();
        }
      });
    }
  });
};

module.exports = onTruncateFileRequested;

@@ -238,16 +238,61 @@
 rict';%0A%0A
+var util = require('../../../shared/util');%0A%0A
 /**%0A * R
@@ -1068,24 +1068,25 @@
 ayBuffer();%0A
+%0A
       var tr
@@ -1087,54 +1087,35 @@
 var 
-trunca
+wri
 te
-d
  = 
-buffer.slice(0, options.length);%0A%0A
+function(data) %7B%0A  
     
@@ -1160,24 +1160,26 @@
 s(%7B%0A        
+  
 Key: path,%0A 
@@ -1189,25 +1189,24 @@
     
+  
 Body: 
-truncated,%0A
+data,%0A  
     
@@ -1228,17 +1228,12 @@
 th: 
-truncated
+data
 .byt
@@ -1246,21 +1246,25 @@
 h%0A      
+ 
+ 
 %7D);%0A%0A
+  
       s3
@@ -1324,24 +1324,26 @@
 ) %7B%0A        
+  
 if (error) %7B
@@ -1339,24 +1339,26 @@
 f (error) %7B%0A
+  
           on
@@ -1378,24 +1378,26 @@
 ');%0A        
+  
 %7D else %7B%0A   
@@ -1389,24 +1389,26 @@
    %7D else %7B%0A
+  
           on
@@ -1430,16 +1430,18 @@
     
+  
 %7D%0A      
 %7D);%0A
@@ -1436,20 +1436,375 @@
 %7D%0A      
+ 
+ 
 %7D);%0A
+      %7D;%0A%0A      if (options.length %3C buffer.byteLength) %7B%0A        // Truncate.%0A        write(buffer.slice(0, options.length));%0A      %7D else %7B%0A        // Pad with null bytes.%0A        var diff = options.length - buffer.byteLength;%0A        var blob = new Blob(%5Bbuffer, new Array(diff + 1).join('%5C0')%5D);%0A        util.blobToArrayBuffer(blob, write);%0A      %7D%0A
     %7D%0A  

fix s3 truncate for the extend case