var page = require('webpage').create(),
  system = require('system'),
  fs = require('fs'),
  width = "800",
  height = "450",
  viewportWidth = "600",
  viewportHeight = "330",
  marginTop = 0,
  marginRight = 0,
  marginBottom = 0,
  marginLeft = 0,
  headerHeight = 0,
  footerHeight = 0,
  operatingSystem = "linux",
  arg1 = system.args[ 1 ],
  sourcePath = system.args[ 2 ],
  activityUrl = system.args[ 3 ],
  coordinates = system.args[ 3 ],
  targetBgPath = system.args[ 4 ],
  targetFgPath = system.args[ 5 ],
  targetPath = system.args[ 6 ],
  jsWait = 20000,
  paddingLeft = 0,
  paddingTop = 0,
  jsInterval = 100;

var elevation_pendence = 0;

if(arg1 == "segment") {
  width = "600";
  height = "600";
  viewportWidth = "300";
  viewportHeight = "300";
  elevation_pendence = system.args[ 7 ];
}
if(arg1 == "activity"){
  viewportWidth = "800";
  viewportHeight = "450";
}
if(arg1 == "route") {

  paddingLeft = 400;
  paddingTop = 50;
}

// this function writes the arguments to stdout
var log = function () {
  Array.prototype.slice.call(arguments).map(system.stdout.writeLine);
};

// this function writes the arguments to the stderr
var err = function () {
  Array.prototype.slice.call(arguments).map(system.stderr.writeLine);
};

// this function checks to see if javascript is finished executing on the page
var done = function () {
  return page.evaluate(function () {
    var PageRendered = window.PageRendered;
    return (typeof PageRendered === 'undefined') ||
      (typeof PageRendered === 'boolean' && PageRendered === true) ||
      (typeof PageRendered === 'function' && PageRendered());
  });
};

// this sets a zoom on the page because of the dpi differences between windows and unix
var setZoom = function () {
  try {
    page.evaluate(function () {
      //document.body.style.zoom = 2;
      //document.body.style.webkitTransform = "scale(2)";
      //document.body.style.webkitTransformOrigin = "0% 0%";
    });
  } catch (error) {
    err('Failed to set zoom on HTML file: ', error);
    phantom.exit(2);
  }
};

// this function renders the page
var renderPage = function () {
  setZoom();

  // render the page
  try {
    log('Rendering PDF to target path: ' + targetPath);
    page.render(targetPath);
    page.evaluateJavaScript("function(){window.hideMapBackGround();return;}");
    if(arg1 != "route") {
      setTimeout(function() {
        page.render(targetFgPath);
        page.evaluateJavaScript("function(){window.showMapBackGround();return;}");
      }, 200);
      
      setTimeout(function() {
        page.render(targetBgPath);
        phantom.exit(0);
      }, 400);
    }else {
      phantom.exit(0);
    }
    
  } catch (error) {
    err('Failed to render PDF: ' + error);
    phantom.exit(3);
  }
};


page.viewportSize = { width: viewportWidth, height: viewportHeight };

var getFn = function (str) {
  return eval('var fn = ' + str + '; fn');
};

var paperSize = {
  width: width,
  height: height,
  margin: {
    top: marginTop,
    right: marginRight,
    bottom: marginBottom,
    left: marginLeft
  }
};

page.paperSize = paperSize;

// log all the resource requests
page.onResourceRequested = function (requestData, request) {
  log('Loading URL: ' + requestData[ 'url' ]);
};
page.onResourceError = function(resourceError) {
  err('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
  err('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
};

var waited = 0;
var renderIfDone = function renderIfDone() {
  if (done()) {
    renderPage();
  } else {
    if (waited > jsWait) {
      err('Timed out on JavaScript execution');
      phantom.exit(6);
    }
    log('Waiting an additional ' + jsInterval + 'ms');
    waited += jsInterval;
    setTimeout(renderIfDone, jsInterval);
  }
};

var preRenderDone = function() {
  
  if(arg1 == "activity"){
    
    page.evaluateJavaScript("function(){window.startMap('"+ activityUrl +"');return;}");
    renderIfDone();
  }
  if(arg1 == "segment") {
    page.evaluateJavaScript("function(){window.startSegmentMap('"+ activityUrl +"', "+elevation_pendence+");return;}");
    renderIfDone();
  }

  if(arg1 == "route") {
    page.evaluateJavaScript("function(){window.startRouteMap('"+ activityUrl +"');return;}");
    renderIfDone();
  }
  
};

// when finishing loading the resources
// start the timer for js execution to complete
page.onLoadFinished = preRenderDone;

try {

  log('Reading source file: ' + sourcePath);
  page.content = fs.read(sourcePath, { encoding: 'utf-8' });
} catch (error) {
  err('Failed to read source file: ' + error);
  phantom.exit(1);
}