/*
	Licensed Material - Property of IBM

	(C) Copyright 2016 IBM Corp.

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/


'use strict';

//public modules
var fs = require('fs');
var log = require('npmlog');
var path = require('path');
var Q = require('q');

var moduleName = 'copyWWWFolder';


// List of files and directory names to NOT copy from the application platform's www
// folder into the 'zip' folder
var excludeFilesDirs = ['.DS_Store', '.jazzignore', '.gitignore', '.gitattributes', 'Thumbs.db'];

/**This funciton copies over a Cordova platforms www folder to a temporary directory,
*  for IOS this www folder is /platforms/ios/www
*  for Android this www folder is /platforms/android/assets/www
**/
module.exports = function (platform, tmpdir) {
  var d = Q.defer();

  log.silly(moduleName, 'creating www folder inside of tmpdir');
  var wwwTmpDir = path.resolve(tmpdir, 'www');
  fs.mkdirSync(wwwTmpDir);

  //The three various windows platforms all live under platforms/windows, so we check that a platform is windows, if not we just use what platform was sent in
  var rootPlatform = platform.platform.indexOf('windows') >= 0 ? 'windows' : platform.platform;
  var wwwFolderPath = path.resolve(platform.configXMLPath, '..', 'platforms', rootPlatform);
  if(platform.platform === 'android') {
    wwwFolderPath = path.resolve(wwwFolderPath, 'assets/www');
  } else {
    wwwFolderPath = path.resolve(wwwFolderPath, 'www');
  }

  try {
    var unpackedDirSize = _copydir(wwwFolderPath, wwwTmpDir, _zipFileFilter);
    d.resolve(unpackedDirSize);
  } catch (err) {
    d.reject(err);
  }

  return d.promise;
};

// Recursively copies contents from one directory into another
// A filefilter can be provided to restrict files/dirs from being copied
// Target todir is not cleaned prior to the copy.
function _copydir(fromdir, todir, filefilter) {
    var unpackedDirSize = 0;

    log.silly('_copydir', 'copying dir '+fromdir+' to '+todir);
    var dirContents = fs.readdirSync(fromdir);
    for(var i=0; i<dirContents.length; i++) {
        var file = dirContents[i];
        var filepath = path.join(fromdir,file);
        //log.silly('_copydir', 'examining '+filepath);
        if (!filefilter || filefilter(filepath)) {
            var fsstats = fs.statSync(filepath);
            if (fsstats.isDirectory()) {
                log.silly('_copydir', 'creating subdir '+filepath);
                fs.mkdirSync(path.join(todir,file));
                _copydir(filepath, path.join(todir,file), filefilter);
            }
            else if (fsstats.isFile()) {
                //log.silly('_copydir', 'copying file '+file);
                fs.writeFileSync(path.join(todir,file), fs.readFileSync(path.join(fromdir,file)));
                unpackedDirSize += fsstats.size;
            }
        }
        else {
            log.silly('_copydir', 'ignoring '+file);
        }
    }

    log.silly('_copydir', 'return unpacked dir size: ' + unpackedDirSize);
    return unpackedDirSize;
}

// zip file filter.  Used to control the directories and files being
// copied from the source application folder into the 'zip' folder
function _zipFileFilter(file) {
    var basefile = path.basename(file);
    //log.silly('_zipFileFilter', 'filter check: '+basefile);
    return (excludeFilesDirs.indexOf(basefile) === -1);
}
