var db = null;

document.addEventListener('ready', function() {
//  alert("ready");

});
$(document).ready(function(){
  //alert("ready");
  //db = window.openDatabase({name: 'westing.sqlite', location: 'default'});
  //db = window.sqlitePlugin.openDatabase({name: 'westing.sqlite', location: 'default'});
  db = openDatabase('westing.sqlite', '1.0', 'Test DB', 2 * 1024 * 1024);
  alert("ready");
});

function executeSQL(sqlQuery, callback){
  db.transaction(function (tx) {
   tx.executeSql(sqlQuery,null,
      function(trans,result){
        //console.log({Status:"Executed", Query: sqlQuery , Result: result, Transaction: trans});
        callback(result);
      },
      function(error){
        console.log({Status:"Error", Query: sqlQuery , Error: error});
        callback(error);
      });

        //callback(error);
  });

}
function prepareDB(callback){
  $.get("schema.txt", function(lines){
    lines = lines.split('\n');
    for(var i = 0;i < lines.length;i++){
      console.log(i == lines.length-1);
      if(i == lines.length-1){
        queryQueue.push(lines[i]);
      }else{
        queryQueue.push(lines[i]);
      }

    }
  });
}
function populateAllDB(){
  populateDB("CUSTOMER",
    populateDB("INVENTORY",
      populateDB("ORDER_HEAD",
        populateDB("ORDER_DETAIL",
          populateDB("INVOICE_HEAD",
            populateDB("INVOICE_DETAIL", console.log))))));
}
function prepareAllServerFiles(){
  prepareServerFiles("CUSTOMER",
    prepareServerFiles("INVENTORY",
      prepareServerFiles("ORDER_HEAD",
        prepareServerFiles("ORDER_DETAIL",
          prepareServerFiles("INVOICE_HEAD",
            prepareServerFiles("INVOICE_DETAIL"))))));
}
var queryQueue = [];
var queryQueueIndex = 0;
var queryQueueMax = 0;
var listOfTables = ["CUSTOMER" , "INVENTORY", "ORDER_HEAD", "ORDER_DETAIL", "INVOICE_HEAD", "INVOICE_DETAIL"];
var tableIndex = 0;
function prepareNextTableFile(){
  if(tableIndex < listOfTables.length){
    prepareServerFiles(listOfTables[tableIndex++],prepareNextTableFile);
  }else{
    populateAllDB();
  }

}
function populateNextTableFile(){

}
function runQueryQueue(){
  if(query = queryQueue.shift()){
    $('[name=sku]').val(queryQueue.length/queryQueueMax);
    if(queryQueueIndex === 0){
      queryQueueMax = queryQueue.length+1;
    }
    queryQueueIndex++;
    $('#queryQueueCount').val(queryQueue.length);
    executeSQL(query, runQueryQueue);
  }
}
function prepareServerFiles(table, callback){
  var salesman = "RP";
  var rootURL = 'https://www.westingpr.com/';
  switch (table) {
    default:
      $.get(rootURL + "getData.php?t=" + table + "&sm="+salesman, function(data){
        data = JSON.parse(data);
        if(data.Result){
          callback;
        }
      });
    break;
    case "INVENTORY":
      $.get(rootURL + "getData.php?t=" + table + "&sm="+salesman, function(data){
        data = JSON.parse(data);
        if(data.Result){
          callback;
        }
      });
    break;
    case "ORDER_HEAD":
      $.get(rootURL + "getData.php?t=" + table + "&sm="+salesman, function(data){
        data = JSON.parse(data);
        if(data.Result){
          callback;
        }
      });
    break;
    case "ORDER_DETAIL":
      $.get(rootURL + "getData.php?t=" + table + "&sm="+salesman, function(data){
        data = JSON.parse(data);
        if(data.Result){
          callback;
        }
      });
    break;
    case "INVOICE_HEAD":
      $.get(rootURL + "getData.php?t=" + table + "&sm="+salesman, function(data){
        data = JSON.parse(data);
        if(data.Result){
          callback;
        }
      });
    break;
    case "INVOICE_DETAIL":
      $.get(rootURL + "getData.php?t=" + table + "&sm="+salesman, function(data){
        data = JSON.parse(data);
        if(data.Result){
          callback;
        }
      });
    break;
  }

}
function populateDB(table, callback){
  var rootURL = 'https://www.westingpr.com/sync/';
  var salesman = "RP";
  switch (table) {
    case "CUSTOMER":
      $.get( rootURL + salesman + ".CUSTOMER.syncFile", function(data){
        var lines = data.split('\n');
        for(var i = 0;i < lines.length;i++){
          if(lines[i] !== ""){
            var sql = "INSERT INTO CUSTOMER VALUES (" + lines[i] + ")";
            queryQueue.push(sql);

            // executeSQL(sql, function(result){
            //   callback;
            //   if(result.Status == "Executed"){
            //     var rows = result.Result.rows;
            //     for(var i = 0; i > rows.lenght; i++){
            //       //console.log(row[i]);
            //     }
            //   }
            // });

          }
        }
        callback;
      });
      break;
    case "INVENTORY":
      $.get( rootURL + salesman + ".INVENTORY.syncFile", function(data){
        var lines = data.split('\n');
        for(var i = 0;i < lines.length;i++){
          var sql = "INSERT INTO INVENTORY VALUES (" + lines[i] + ")";
          queryQueue.push(sql);
          // executeSQL(sql, function(result){
          //   if(result.Status == "Executed"){
          //     var rows = result.Result.rows;
          //     for(var i = 0; i > rows.lenght; i++){
          //       console.log(row[i]);
          //     }
          //   }
          // });

        }
        callback;
      });
      break;
    case "ORDER_HEAD":
      $.get( rootURL + salesman + ".ORDER_HEAD.syncFile", function(data){
        var lines = data.split('\n');
        for(var i = 0;i < lines.length;i++){
          var sql = "INSERT INTO ORDER_HEAD VALUES (" + lines[i] + ")";
          queryQueue.push(sql);
          // executeSQL(sql, function(result){
          //   if(result.Status == "Executed"){
          //     var rows = result.Result.rows;
          //     for(var i = 0; i > rows.lenght; i++){
          //       console.log(row[i]);
          //     }
          //   }
          // });
        }
        callback;
      });
      break;
    case "ORDER_DETAIL":
      $.get( rootURL + salesman + ".ORDER_DETAIL.syncFile", function(data){
        var lines = data.split('\n');
        for(var i = 0;i < lines.length;i++){
          var sql = "INSERT INTO ORDER_DETAIL VALUES (" + lines[i] + ")";
          queryQueue.push(sql);
          // executeSQL(sql, function(result){
          //   if(result.Status == "Executed"){
          //     var rows = result.Result.rows;
          //     for(var i = 0; i > rows.lenght; i++){
          //       console.log(row[i]);
          //     }
          //   }
          // });
        }
        callback;
      });
      break;
    case "INVOICE_HEAD":
      $.get( rootURL + salesman + ".INVOICE_HEAD.syncFile", function(data){
        var lines = data.split('\n');
        for(var i = 0;i < lines.length;i++){
          var sql = "INSERT INTO INVOICE_HEAD VALUES (" + lines[i] + ")";
          queryQueue.push(sql);
          // executeSQL(sql, function(result){
          //   if(result.Status == "Executed"){
          //     var rows = result.Result.rows;
          //     for(var i = 0; i > rows.lenght; i++){
          //       console.log(row[i]);
          //     }
          //   }
          // });
        }
        callback;
      });
      break;
    case "INVOICE_DETAIL":
      $.get( rootURL + salesman + ".INVOICE_DETAIL.syncFile", function(data){
        var lines = data.split('\n');
        for(var i = 0;i < lines.length;i++){
          var sql = "INSERT INTO INVOICE_DETAIL VALUES (" + lines[i] + ")";
          queryQueue.push(sql);
          // executeSQL(sql, function(result){
          //   if(result.Status == "Executed"){
          //     var rows = result.Result.rows;
          //     for(var i = 0; i > rows.lenght; i++){
          //       console.log(row[i]);
          //     }
          //   }
          // });
        }
        callback;
      });
      break;
    default:

  }
}
$('[name=inventorySearch]').submit(function(){

  return false;

});
function search(){
  var Line = $("#lineSelect").val();
  var Group = $("#groupSelect").val();
  if(Line === ""){
    Line = "%";
  }
  if(Group === ""){
    Group = "%";
  }
  var SKU = $("[name=sku]").val();
  searchItems(Line, Group, SKU);
}
function fillResult(rows){
  $('.item_result').html('');
  if(rows.length > 0){
    //var rows = result.rows;
    for(var i = 0; i < rows.length; i++){
      //alert(JSON.stringify(rows.item(i)));
      console.log(rows.item(i));
      var result_item = rows.item(i);

      var elem = $('<div/>').addClass("col-md-3").append(
        $("<div/>").css("height", "450px").addClass("thumbnail").append(
          $("<a/>").attr("onclick","getProductDetails('" + result_item.Line + "','" + result_item.SKU + "'); return false;").append(
            $("<img/>").attr("src", "../img/catalog/" + result_item.Line + " " + result_item.SKU + ".jpg").css("max-height", "252px")
          ),
          $("<div/>").addClass("caption").append(
            $("<h4/>").addClass("pull-right").text(moneyFormat(result_item.PriceA)),
            $("<h4/>").append(
              $("<a/>").text(result_item.SKU)
            ),
            $("<p/>").text(result_item.Description)
          ),
          $('<p/>'),
          $('<div/>').addClass("row").append(
            $("<div/>").addClass("col-xs-6"),
            $("<div/>").addClass("col-xs-6")
          )
        )
      );
      console.log(elem);
      $('.item_result').append(elem);
    }
  }
}
function searchItems(Line, Group, SKU){
  var sql = "SELECT * FROM INVENTORY WHERE `Line` LIKE '" + Line + "' AND `Group` LIKE '" + Group + "' AND SKU LIKE '" + SKU + "%'";
  var sql = "SELECT * FROM INVENTORY WHERE `Line` LIKE '" + Line + "' AND `Group` LIKE '" + Group + "' AND (SKU LIKE '" + SKU + "%' OR Description LIKE '%" + SKU + "%' OR Interchange LIKE '" + SKU + "%') AND Active = 1 AND (Discontinued = 0 OR Qty > 0)";
  executeSQL(sql, function(result){
    console.log(result.rows.length);
    fillResult(result.rows);
 });
}
