'use strict';
const fs = require('fs');

function modifyBundleFile(bundlejs) {
  let bundle = fs.readFileSync(bundlejs, { encoding: 'utf-8' });
  if (bundle.length == 0) throw new Error('Empty AST input');
  const searchState = /this.setState/g;
  const wrappedFunc = 'wrapper(this.setState)';
  const searchElem = /(getElementById\([\'\"])\w+[\'\"]/;
  const newMount = 'getElementById("preview"';
  let replacedState = bundle.replace(searchState, wrappedFunc);
  return replacedState.replace(searchElem, newMount);
}

function modifyTestBundleFile(bundle) {
  if (bundle.length == 0) throw new Error('Empty AST input');
  const searchState = /this.setState/g;
  const wrappedFunc = 'wrapper(this.setState)';
  const searchElem = /(getElementById\([\'\"])\w+[\'\"]/;
  const newMount = 'getElementById("preview"';
  let replacedState = bundle.replace(searchState, wrappedFunc);
  return replacedState.replace(searchElem, newMount);
}


module.exports = {
  modifyBundleFile,
  modifyTestBundleFile,
};


@@ -32,16 +32,90 @@
 e('fs');
+%0Aconst regexLastIndexOf = require('./stringRegexHelper').regexLastIndexOf;
 %0A%0Afuncti
@@ -1003,16 +1003,1052 @@
 nt);%0A%7D%0A%0A
+function getComponentName(bundle, startingIndex) %7B%0A  let bundleSearchIndicesMap = %7B%7D;%0A  // get index of component declaration%0A  bundleSearchIndicesMap%5BregexLastIndexOf(bundle, /var %5Cw+ = %5C(%5Cd+, _react.createClass%5C)/, startingIndex)%5D = 'GULP';%0A  // let's try web pack...%0A  bundleSearchIndicesMap%5BregexLastIndexOf(bundle, /var %5Cw+ = function %5C(_React%5C$Component%5C)/, startingIndex)%5D = 'WEBPACK';%0A  %0A  const targetIndex = Object.keys(bundleSearchIndicesMap)%0A  %09.filter(index =%3E index %3E= 0)%0A  %09.reduce((prev, curr) =%3E %7B%0A  %09  return Math.abs(curr-startingIndex) %3C Math.abs(prev-startingIndex)%0A  %09  %09? curr%0A  %09  %09: prev;%0A  %09%7D);%0A %0A  let componentMatch;%0A  switch(bundleSearchIndicesMap%5BtargetIndex%5D) %7B%0A  %09case 'GULP':%0A  %09  componentMatch = bundle.slice(targetIndex)%0A  %09  %09.match(/var %5Cw+ = %5C(%5Cd+, _react.createClass%5C)/)%0A  %09  break;%0A    case 'WEBPACK':%0A   %09  componentMatch = bundle.slice(targetIndex)%0A  %09    .match(/var %5Cw+ = function %5C(_React%5C$Component%5C)/)%0A   %09  break;%0A    default:%0A    %09break;%0A  %7D%0A  return componentMatch%5B0%5D.split(' ')%5B1%5D;%0A%7D%0A
 %0Amodule.
@@ -2103,12 +2103,37 @@
 leFile,%0A
+  modifySetStateStrings,%0A
 %7D;%0A%0A

add getComponentName helper function