/* AutoDoc Javascript */

var conf = {
  default_hash: "home",
  openapi: "/v1",
  pageinit: {
    home: "page_load_home()",
    upload: "page_load_upload()"
  },
  home: {
    width: 4,
    curpage: 0,
    end: 0
  },
  run: {
    "upload_handler": 0,
    "upload_status": 0
  }
};

var temp = {
  upload: [],
  documentid: null
};

$(document).ready(function () {

  change_page();
  upload_zone_init();

  $(document).scroll(function () {
    page_home_scroll();
  });

  $('#autodoc_home_modal_left').mouseenter(function (e) {
    $(e.target).fadeTo("slow", 0.8);
  })
    .mouseleave(function (e) {
      $(e.target).fadeTo("slow", 0.15);
    })
    .click(function (e) {
      home_modal_page_prev();
    });

  $('#autodoc_home_modal_right').mouseenter(function (e) {
    $(e.target).fadeTo("slow", 0.8);
  })
    .mouseleave(function (e) {
      $(e.target).fadeTo("slow", 0.15);
    })
    .click(function (e) {
      home_modal_page_next();
    });

});

$(window).bind("hashchange", function () {
  change_page();
});

function change_page() {
  var hash = document.location.hash.substr(1) || conf.default_hash;

  if (!$("#autodoc_tab_" + hash).length) {
    hash = conf.default_hash;
  }

  /* change menu highlights and content visibility */
  $("#autodoc_navbar")
    .find("a")
    .each(function (id, obj) {
      var curhash = $(obj)
        .attr("href")
        .substr(1);
      if (curhash == hash) {
        $(obj)
          .parent()
          .addClass("active");
        $("#autodoc_tab_" + curhash).removeClass("d-none");
      } else {
        $(obj)
          .parent()
          .removeClass("active");
        $("#autodoc_tab_" + curhash).addClass("d-none");
      }
    });

  if (conf.pageinit[hash]) {
    eval(conf.pageinit[hash]);
  }
}

function isvisible(obj) {
  var top_of_fileent = $(obj).offset().top;
  var bottom_of_fileent = $(obj).offset().top + $(obj).outerHeight();
  var bottom_of_screen = $(window).scrollTop() + $(window).innerHeight();
  var top_of_screen = $(window).scrollTop();

  if (bottom_of_screen > top_of_fileent && top_of_screen < bottom_of_fileent) {
    return true;
  }
  return false;
}

function page_load_home() {
  document_load();
}

function page_load_upload() {
  upload_status();
}

function document_load() {
  if (conf.home.curpage == 0) {
    $("#autodoc_home_body").html("");
  }

  var tmpl = $("#autodoc_template_home");
  var row = $(tmpl)
    .find(".autodoc_template_home_row")
    .clone();

  $.getJSON(
    conf.openapi +
    "/documents?pageSize=" +
    conf.home.width +
    "&pageIndex=" +
    conf.home.curpage,
    null,
    function (data, textStatus, jqXHR) {
      // last document was loaded, stop scrolling
      if (data.length < conf.home.width) {
        conf.home.end = 1;
      }
      $.each(data, function (id, doc) {
        var col = $(tmpl)
          .find(".autodoc_template_home_col")
          .clone();
        $(col)
          .find(".autodoc_template_home_img")
          .attr(
            "src",
            conf.openapi +
            "/documents/" +
            doc.id +
            "/image?maxWidth=" +
            Math.floor(1000 / conf.home.width)
          );
        $(col).find(".autodoc_template_home_img").data("documentId", doc.id);
        $(col).find(".autodoc_template_home_img").on('click', function (e) {
          home_modal_open($(e.target).data("documentId"));
        });

        $(col)
          .find(".autodoc_template_home_owner")
          .html(doc.owner);

        $(col)
          .find(".autodoc_template_home_created")
          .html(doc.created);

        $(col)
          .find(".autodoc_template_home_name")
          .html(doc.name);

        $(col)
          .find(".autodoc_template_home_pages")
          .html(doc.pageId.length);

        $.each(doc.tags, function (id, tag) {
          $(col)
            .find(".autodoc_template_home_tag")
            .after(
              $(col)
                .find(".autodoc_template_home_tag")
                .clone()
                .html(tag)
            );
        });
        $(row).append(col);
      });
      $("#autodoc_home_body").append(row);
      // continue to load until out of browser.
      page_home_scroll();
    }
  );
}

function page_home_scroll() {
  // don't scroll if we've loaded the last document
  if (conf.home.end) {
    return;
  }
  if (isvisible($(".autodoc_template_home_col").last())) {
    console.log("scroll to page " + conf.home.curpage);
    conf.home.curpage++;
    document_load();
  }
}

function upload_zone_init() {
  $(window).on("dragover dragleave drop", function (e) { e.preventDefault() });

  $('.autodoc_upload_zone').on({
    dragenter: upload_zone_highlight,
    dragleave: upload_zone_normal,
    dragover: upload_zone_over,
    drop: upload_zone_drop
  });
}

function upload_zone_highlight(e) {
  $(e.target).addClass('autodoc_upload_zone_hover');
}

function upload_zone_over(e) {
  return true;
}

function upload_zone_normal(e) {
  $(e.target).removeClass('autodoc_upload_zone_hover');
}

function upload_zone_drop(e) {
  var ev = e.originalEvent;

  $.each(ev.dataTransfer.files, function (id, file) {
    console.log(file);
    var fileid = temp.upload.length;
    temp.upload.push({
      progress: 0,
      error: null,
      obj: file
    });
    upload_zone_normal(e);
  });

  if (conf.run.upload_handler == 0) {
    upload_handler();
  }

  if (conf.run.upload_status == 0) {
    upload_status();
  }

}

function upload_handler() {
  var stop = 1;
  conf.run.upload_handler = 1;
  console.log("upload_handler");
  if (temp.documentid == null) {
    console.log("creating documentId");
    $.post(conf.openapi + "/documents", {}, function (data) {
      temp.documentid = data.id;
    });
    stop = 0;
  }
  else {

    for (var id = 0; id < temp.upload.length; id++) {
      var file = temp.upload[id];
      if (file.progress != 100) {
        if (file.progress == 0) {
          if (file.obj.type != 'application/pdf' && file.obj.type != 'image/png' && file.obj.type != 'image/jpeg') {
            file['progress'] = 100;
            file['error'] = 'invalid file type';
          }
          else {
            var reader = new FileReader();
            file['progress'] = 1;

            $(reader).on('load', id, upload_read_event);
            $(reader).on('loadstart', id, upload_read_event);
            $(reader).on('loadend', id, upload_read_event);
            $(reader).on('progress', id, upload_read_event);
            $(reader).on('error', id, upload_read_event);
            $(reader).on('abort', id, upload_read_event);

            reader.readAsArrayBuffer(file.obj);
          }
        }
        stop = 0;
        break;
      }
    }
  }
  if (stop) {
    conf.run.upload_handler = 0;
  }
  else {
    setTimeout(function () { upload_handler(); }, 500);
  }
}

function upload_read_event(e) {
  if (e.type == 'progress') {
    if (e.lengthComputable) {
      var progress = Math.floor(e.originalEvent.loaded / e.originalEvent.total * 50);
      if (progress < 1) { progress = 1; }
      if (progress > 49) { progress = 49; }
      temp.upload[e.data]['progress'] = progress;
    }
  }
  else if (e.type == 'load') {

    temp.upload[e.data]['progress'] = 50;
    console.log(e.target.result);
    console.log("upload_id", e.data);
    $.ajax({
      type: 'POST',
      url: conf.openapi + "/documents/" + temp.documentid + "/data",
      data: e.target.result,
      contentType: temp.upload[e.data].obj.type,
      context: { id: e.data },
      processData: false,
      xhr: function () {
        var xhr = $.ajaxSettings.xhr();
        xhr.upload.addEventListener("progress", (function () {
          var id = e.data;
          return function (evt) {
            if (evt.lengthComputable) {
              var progress = Math.floor(evt.loaded / evt.total * 50);
              if (progress < 1) { progress = 1; }
              if (progress > 49) { progress = 49; }
              temp.upload[id].progress = 50 + progress;
              // console.log("upload_progress_event", evt);
            }
          }
        })(), false);
        return xhr;
      },
      success: function (data, status, xhr) {
        console.log("upload_success_this", this);
        temp.upload[this.id].progress = 100;

      }
    });
  }
}

function upload_status() {
  var stop = 1;

  conf.run.upload_status = 1;

  $.each(temp.upload, function (id, file) {
    if (!$('.autodoc_upload_status_' + id).length) {
      var obj = $(".autodoc_template_progress").children().clone();
      $(obj).addClass('autodoc_upload_status_' + id);
      $('.autodoc_upload_status').append(obj);
      stop = 0;
    }
    var obj = $('.autodoc_upload_status_' + id).children();
    if (file.error != null) {
      $(obj).html(file.obj.name + ': ' + file.error);
      $(obj).css('width', '100%');
      $(obj).addClass('bg-danger');
      $(obj).removeClass("progress-bar-animated");
      $(obj).removeClass("progress-bar-striped");

    }
    else if (file.progress == 100) {
      $(obj).html(file.obj.name);
      $(obj).css('width', '100%');
      $(obj).addClass('bg-success');
      $(obj).removeClass('progress-bar-animated');
      $(obj).removeClass("progress-bar-striped");
    }
    else if (file.progress < 50) {
      $(obj).html(file.obj.name + ': ' + 'reading file');
      $(obj).css('width', file.progress + '%');
      stop = 0;
    }
    else {
      $(obj).html(file.obj.name + ': ' + 'sending file');
      $(obj).css('width', file.progress + '%');
      stop = 0;
    }
  });

  if (stop) {
    conf.run.upload_status = 0;
  }
  else {
    setTimeout(function () { upload_status(); }, 100);
  }
}


function home_modal_page(pageNum) {
  var doc = $('#autodoc_home_modal').data('document');
  var pageTotal = doc.pageId.length;

  if ( pageNum < 0 ) {
    pageNum=pageTotal-1;
  }

  if ( pageNum > pageTotal - 1 ) {
    pageNum = 0;
  }

  $('.autodoc_home_modal_page').html(pageNum+1);
  $('#autodoc_home_modal').data('pageNum', pageNum);

  $('#autodoc_home_modal_img').attr('src',
    conf.openapi +
    "/pages/" +
    doc.pageId[pageNum] +
    "/image");
}

function home_modal_page_prev() {
  home_modal_page(
    $('#autodoc_home_modal').data('pageNum') - 1);
}

function home_modal_page_next() {
  home_modal_page(
    $('#autodoc_home_modal').data('pageNum') + 1);
}

function home_modal_open(docid) {
  $.getJSON(conf.openapi + "/documents/" + docid, function (data) {
    $('#autodoc_home_modal').data('document', data);
    console.log(data);
    var pageNum;
    for (var i = 0; i < data.pageId.length; i++) {
      if (data.pageId[i] == data.primaryPage) {
        pageNum = i;
        break;
      }
    }
    $('.autodoc_home_modal_name').html(data.name ? data.name : 'n/a');
    $('.autodoc_home_modal_created').html(data.created);
    $('.autodoc_home_modal_languages').html(data.languages.join(' '));
    $('.autodoc_home_modal_pages').html(data.pageId.length);
    $('.autodoc_home_modal_owner').html(data.owner);

    home_modal_page(pageNum);

    $('#autodoc_home_modal').modal('show');
  });
}

function home_modal_close(docid) {
  $('#autodoc_home_modal').modal('hide');
}
