import {EtrackerUtils} from "./EtrackerUtils";



export class UiUtils {
  static initUI() {

    UiUtils.initPrintDialog();
    UiUtils.initfileupload();
    UiUtils.initTrackEventElementAnalytics();
    UiUtils.disbaleInitialForNewsletterSubPage();
    UiUtils.initEtrackerOnCookiebotEvent();
    UiUtils.initEtrackerOnUsercentricsEvent();
    UiUtils.initEmptyAnchorLinks();
  }

  static initEtrackerOnCookiebotEvent() {
    if (typeof ihk !== "undefined" && ihk.settings && ihk.settings.etrackerCookieless === false) {
      window.addEventListener('CookiebotOnConsentReady', EtrackerUtils.initEtrackerCookies, false);
    }
  }

  static initEtrackerOnUsercentricsEvent() {
    window.addEventListener('onConsentStatusChange', EtrackerUtils.initEtrackerUsercentricsCookies, false);
  }


  static initTrackEventElementAnalytics() {
    if (!window.isPbe) {
      $(".trackEventElement").each(
        function () {
          const category = $(this).data(
            'analytics-category');
          const object = $(this).data('analytics-object');
          const action = $(this).data('analytics-action');
          const tags = $(this).data('analytics-tags');
          window.setTimeout(EtrackerUtils.fireETrackerEvent, 250,
            category, object, action, tags);
        });
    }
  }

  static disbaleInitialForNewsletterSubPage() {
    const inxForm = $(".inxform");
    const inxHolderText = $(inxForm).closest(".detail-text");

    if (inxHolderText.length > 0) {
      inxHolderText.find(".text").first().addClass("no-initial");
    }
  }

  static initfileupload() {
    //todo: make great again
    if (typeof jQuery.fn.fileupload == 'function') {

      var filelist = [], uploadUrl = $('#fileupload')
        .data("url");
      $('#fileupload')
        .fileupload(
          {
            url: uploadUrl,
            previewMaxWidth: "90",
            previewMaxHeight: "90",
            previewCrop: true,
            singleFileUploads: false,
            filesContainer: $('#uploaded-files'),
            uploadTemplateId: null,
            downloadTemplateId: null,
            uploadTemplate: function (o) {
              var rows = $();
              $
                .each(
                  o.files,
                  function (
                    index,
                    file) {
                    var row = $('<div class="mwf-upload-row thumbnail template-upload">'
                      + '  <div class="mwf-upload-fileinfo">'
                      + '    <div class="mwf-upload-preview"><div class="preview"><span></span></div></div>'
                      + '    <div class="mwf-upload-metadata">'
                      + '      <ul>'
                      + '        <li>Name: <span class="name"></span></li>'
                      + '        <li>Größe: <span class="size"></span></li>'
                      + (file.error ? '<li>Fehler: <span class="error"></span></li>'
                        : '')
                      + '      </ul>'
                      + '    </div>'
                      + '  </div>'
                      + '  <div class="mwf-upload-actions">'
                      + '    <div class="cancel"><button>Löschen</button></div>'
                      + '  </div>'
                      + '</div>');
                    row
                      .find(
                        '.name')
                      .text(
                        file.name);
                    row
                      .find(
                        '.size')
                      .text(
                        o
                          .formatFileSize(file.size));

                    row
                      .find(
                        'button')
                      .click(
                        function () {
                          for (var i in filelist) {
                            var fileEntry = filelist[i];
                            if (fileEntry.name == file.name) {
                              filelist
                                .splice(
                                  i,
                                  1);
                              $(
                                '.mwf-upload-error')
                                .text(
                                  '');
                              break;
                            }
                          }
                        });

                    rows = rows
                      .add(row);
                  });
              return rows;
            },

            dataType: 'json',
            progressall: function (e, data) {
              var progress = parseInt(
                data.loaded
                / data.total
                * 100, 10);
              $('#progress .bar').css(
                'width',
                progress + '%');
            },
            dropZone: $('#dropzone')

          })
        .on(
          "fileuploadadd",
          function (e, data) {

            var maxFiles = $('#fileupload')
              .data('maxfiles'), maxFilesize = $(
              '#fileupload').data(
              'maxfilesize');

            // letzt Meldung entfernen:
            $('.mwf-upload-error').text('');

            if (filelist.length > (maxFiles - 1)) {
              $('.mwf-upload-error')
                .text(
                  'Hinweis: Es dürfen maximal '
                  + maxFiles
                  + ' Dateien hochgeladen werden.');
              return false;
            } else {
              for (var i = 0; i < data.files.length; i++) {
                filelist
                  .push(data.files[i])
              }

              var totalSize = 0;
              for (var pos in filelist) {
                totalSize += filelist[pos].size;
              }
              if (totalSize > (maxFilesize * 1024 * 1024)) {
                filelist.pop();
                $('.mwf-upload-error')
                  .text(
                    'Hinweis: Die Größe der Dateien überschreitet die maximale Gesamtgröße von '
                    + maxFilesize
                    + 'MB.');
                return false;
              }
            }
          });

      $('#uploadbutton')
        .click(
          function () {
            $('#fileupload')
              .fileupload('send', {
                files: filelist
              }).done(
              function (
                result,
                textStatus,
                jqXHR) {
                if (result.success === true) {
                  $(
                    '.mwf-upload')
                    .html(
                      '<p><strong>Ihre Daten wurden erfolgreich hochgeladen.</strong></p>');
                } else {
                  $(
                    '.mwf-upload')
                    .html(
                      '<p><strong>Es ist ein Fehler aufgetreten: '
                      + result.errors
                      + '</strong></p>');
                }
              }).fail(
              function (
                jqXHR,
                textStatus,
                errorThrown) {
                $(
                  '.mwf-upload')
                  .html(
                    '<p><strong>Es ist ein Fehler aufgetreten: '
                    + errorThrown
                    + '</strong></p>');
              })
              .always(
                function (
                  result,
                  textStatus,
                  jqXHR) {
                  filelist = [];
                })
          });
    }

  }

  static initPrintDialog() {
    if ((window.location.href.indexOf('print=true') !== -1)
      && (window.location.href.indexOf('printsrc=button') !== -1)
      && (window.print !== undefined)) {
      console.log("print load")
      global.$('body').trigger("lazyload-gallery-image");
      // todo: Workaround mit timeout, hier musste auf jedes Bild ein http response event gesetzt werden und async print aufrufen
      setTimeout(() => {
        // wartet auf letztes frame der sich gerade rendert
        requestAnimationFrame(() => {
          window.print()
        });

      }, 1000)

    }

  }

  // IHK-5928 missing link to root channel
  static initEmptyAnchorLinks(){
    $(".main-col .richtext .detail-text a[href='']").attr("href","/");
  }
}
