/* Was this Asset loaded yet, and did the PHP Footer file find this Asset */
function doesAssetExists(filename) {
  let dfd = new tts.DeferredPromise();
  if ( hasLoaded(filename) === true ) {
    dfd.resolve("loaded");
    return dfd;
  }
  var exists = false;
  for (i = 0; i < assets_files.length; i++) {
    if (filename == assets_files[i].filename) {
      debug_print('Loading: ' + filename)
      dfd.resolve(assets_files[i].ts);
      include_once_files.push(filename);
      exists = true;
      break;
    }
  }
  if (exists === false) {
    dfd.reject("skipped");
  }
  return dfd;
}

/* Helper method to apply CSS dynamicly */
function apply_css(href, version) {
  var dfd_css = new tts.DeferredPromise();
  tts.getAsset({name: href, path: ajax_folder, ts: version}).then(val=>{
      dfd_css.resolve("Loaded CSS");
  }).catch(function (err) {
      dfd_css.reject(err);
  });
  return dfd_css;
}

/* Run Main method on Class File */
function do_run_main(obj, req) {
  var dfd_run_main = new tts.DeferredPromise();
  if (obj['Main']) {
    tts.when([obj['Main']()]).then(function () {
      debug_print(obj.constructor.name + ' Main complete');
      dfd_run_main.resolve("Main_ajax_complete");
    });
  } else {
    debug_print(obj.constructor.name + " MAIN FN not found!");
    dfd_run_main.reject('Main FN not found!');
  }
  return dfd_run_main;
}

/* This will Run JS code for Tabs! */
function do_run(obj, req) {
  var dfd_run = new tts.DeferredPromise();
  if (obj[req.params.tab]) {
    tts.when([obj[req.params.tab]()]).then(function () {
      debug_print(obj.constructor.name + ' ' + req.params.tab + ' complete');
      dfd_run.resolve("fn_ajax_complete");
    });
  } else if ( is_404(req.params.tab) ) {
    console.log(obj.constructor.name + " " + req.params.tab + " tab FN not found!");
    do_404_page();
    dfd_run.reject('FN not found!');    
  } else {
    dfd_run.resolve("empty_page"); /* Known empty page */
  }
  return dfd_run;
}

/* Just checks if file has been loaded once yet */
var include_once_files = [];
function hasLoaded(file) {
  if (include_once_files.indexOf(file) === -1) {
    return false;
  } else {
    return true;
  }
}

/* JS Loader */
function loadJS(scriptFile, version, obj, req, fn) {
  var method_fn = window[fn];
  var dfd_loadjs = new tts.DeferredPromise();
  
  tts.getAsset({name: scriptFile, path: ajax_folder, ts: version}).then(val=>{
      tts.when([method_fn(obj, req)]).then(function() {
          dfd_loadjs.resolve("js_complete");
      }).catch(function (exception) {
            method_fn(obj, req);
            dfd_loadjs.reject('Something went wrong');
            console.warn("Something went wrong: " + exception); 
      });
      return dfd_loadjs;        
    });
}

/* Does Class StartUp, CSS, and JS - After Main JS has completed loading... */
function do_other_FN(obj, req) {
  var className = obj.constructor.name;
  if (obj['StartUp']) {
    obj['StartUp']();
  }
  var Script_File = className + "-" + req.params.tab + ".js";
  var CSS_File = className + "-" + req.params.tab + ".css";
  var MainCSS_File = className + "-Main.css"; 
  var dfdScript = doesAssetExists(Script_File);
  dfdScript.then(function (versionNumber) {
    if (versionNumber === 'loaded') {
      do_run(obj, req);
    } else {
      loadJS(Script_File, versionNumber, obj, req, 'do_run');
    }
  }).catch(function (err) {
    do_run(obj, req);
  });
  
  var Main_dfd_CSS = doesAssetExists(MainCSS_File);
  Main_dfd_CSS.then(function (versionNumber) {
    if (versionNumber !== 'loaded') {
      var applied_main_css = apply_css(MainCSS_File, versionNumber);
        tts.when([applied_main_css]).then(function() {
            Main_dfd_CSS.resolve("Added main css");
        });
    }
  }).catch(function (err) {
      Main_dfd_CSS.reject(err);
  });

  var dfdCSS = doesAssetExists(CSS_File);
  dfdCSS.then(function (versionNumber) {
    if (versionNumber !== 'loaded') {
      var applied_css = apply_css(CSS_File, versionNumber);
        tts.when([applied_main_css]).then(function() {
            dfdCSS.resolve("Added CSS");
        });
    }
  }).catch(function (err) {
      dfdCSS.reject(err);
  });
}

/* This is the core loader for Tabs and Main Route */
var cloneObject = {};
function do_tabs(className, req) {
  var myclass = window[className];
  var obj = new myclass(req);
  cloneObject = obj;
  var MainScript_File = className + "-Main.js";
  var Main_dfd_Script = doesAssetExists(MainScript_File);
  Main_dfd_Script.then(function (versionNumber) {
    if (versionNumber === 'loaded') {
      var dfd_main_code = do_run_main(obj, req);
      tts.when([dfd_main_code]).then(function () { do_other_FN(obj, req); });
    } else {
      var dfd_main_code = loadJS(MainScript_File, versionNumber, obj, req, 'do_run_main');
      tts.when([dfd_main_code]).then(function () { do_other_FN(obj, req); });
    }
  }).catch(function (err) {
    var dfd_main_code = do_run_main(obj, req);
    tts.when([dfd_main_code]).then(function () { do_other_FN(obj, req); });
  });
  return true;
}

/* Load 404 JS for doing 404 Page */
function do_404_page() {
  var ErrorScript_File = "PageNotFound-Main.js";
  var err_page = new PageNotFound(false);
  if ( hasLoaded(ErrorScript_File) === true ) {
      err_page.Main();
    } else {
      tts.getAsset({name: ErrorScript_File, path: ajax_folder}).then(val=>{
          include_once_files.push(ErrorScript_File);
          err_page.Main();
      });
    }
}

/* Is 404 on, if so does Tab Method/File exists, if not was an exception made */
function is_404(tab_name) {
  if (do_404_page_on_bad_tabs === false) return false; /* Is 404 off?? */
  for (i = 0; i < empty_tab_pages.length; i++) {
    if (empty_tab_pages[i] == tab_name) {
      return false; /* Found allowed empty tab page */
    }
  }
  return true; /* Unable to find tab page hash in allowed list */
}