// localization
window.GetBrowserLanguage = function ()
{
  return (navigator.languages && navigator.languages.length) ? navigator.languages[0] :
         navigator.userLanguage || navigator.language || navigator.browserLanguage || 'en';
}

window.SetCulture = function (cultureName)
{
  if (!cultureName)
  {
    return;
  }
  
  const script = document.createElement('script');
  script.setAttribute('src', 'assets/scripts/telerik-reportviewer.' + cultureName + '.js');
  document.body.appendChild(script);
}

window.SetKendoCulture = function (cultureName) {
  kendo.culture(cultureName);
}

// nav-menu
window.ToggleMainMenu = function (isVisible)
{
  const mainMenuElement = document.getElementById('main-menu');
  if (isVisible)
  {
    mainMenuElement.classList.add('block');
    mainMenuElement.classList.remove('hidden');
  }
  else
  {
    mainMenuElement.classList.add('hidden');
    mainMenuElement.classList.remove('block');
  }
}


// sound-player
window.PlayAudioFile = (soundName) =>
{
  if (!soundName)
  {
    return;
  }
  let sound  = document.createElement('audio');
  sound.src  = `assets/sounds/${soundName}.mp3`;
  sound.type = 'audio/mpeg';
  document.body.appendChild(sound);
  sound.load();

  sound.play().catch(() =>
                     {
                       sound.remove();
                     });

  sound.onended = _ =>
  {
    sound.remove();
  };
}


// theme-util
function findTelerikLightCssFile()
{
  for (let idx in document.styleSheets)
  {
    const cssFile = document.styleSheets[idx];
    if (cssFile.href && cssFile.href.includes('kendo-theme-material.css'))
    {
      return cssFile;
    }
  }
  return '';
}

window.SetTheme = function (themeId, isLightSubset)
{
  document.documentElement.dataset.theme = themeId;

  const telerikLightCssFile = findTelerikLightCssFile();
  if (telerikLightCssFile)
  {
    telerikLightCssFile.disabled = !isLightSubset;
  }
}

window.SetGridFontFamily = function (fontFamily)
{
    document.documentElement.dataset.gridFontFamily = fontFamily;
}


// clipboard-tool
window.CopyToClipboard = async function (text)
{
  if (navigator.clipboard && window.isSecureContext)
  {
    await navigator.clipboard.writeText(text);
  }
  else
  {
    const textArea = document.createElement("textarea");
    textArea.value = text;

    textArea.style.position = "absolute";
    textArea.style.left     = "-999999px";

    document.body.prepend(textArea);
    textArea.select();

    try
    {
      document.execCommand('copy');
    }
    catch (error)
    {
      console.error(error);
    }
    finally
    {
      textArea.remove();
    }
  }
};

window.PasteFromClipboard = async function ()
{
  if (navigator.clipboard && window.isSecureContext)
  {
    return await navigator.clipboard.readText();
  }
  else
  {
    try
    {

      document.execCommand('paste', false);
    }
    catch (error)
    {
      console.error(error);
    }
  }
}

window.SaveContentAsFile = function (filename, base64Content)
{
  const link     = document.createElement('a');
  link.className = 'hidden';
  link.download  = filename;
  link.href      = 'data:application/octet-stream;base64,' + base64Content;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

window.GetGridRowAvgHeight = function (id)
{
  const gridElement = document.getElementById(id);
  if (!gridElement)
  {
    return -1;
  }

  const rows = [...gridElement.getElementsByClassName("k-master-row")];

  if (rows.length <= 0)
  {
    return -1;
  }

  return rows.reduce((acc, row) => acc + row.getBoundingClientRect().height, 0) / rows.length;
}

// scheme
window.ToggleCanvasUnackedPhase = function (id, isPhaseOn)
{
  const canvas = document.getElementById('canvas-' + id);
  if (!canvas)
  {
    return;
  }
  canvas.style.opacity = (isPhaseOn) ? '.6' : '0';
}

window.SetCanvasCursor = function(id, cursor)
{
    const canvas = document.getElementById('canvas-' + id);
    if (!canvas)
    {
        return;
    }
    canvas.style.cursor = cursor;
}

window.EnsureCanvasTooltipPosition = function (id, pointerX, pointerY)
{
    const padding = 5;
    const tooltip = document.getElementById('canvas-tooltip-' + id);
    if (!tooltip)
    {
        return;
    }
    tooltip.style.visibility = 'hidden';
    tooltip.style.left = '-10000px';
    tooltip.style.top = '-10000px';
    const originalRect = tooltip.getBoundingClientRect();
    tooltip.style.left = `${pointerX + padding}px`;
    tooltip.style.top = `${pointerY + padding}px`;
    const positionedRect = tooltip.getBoundingClientRect();
    const containerWidth = window.innerWidth;
    const containerHeight = window.innerHeight;
    if (positionedRect.right > containerWidth) // не влезла ширина - справа от экрана
    {
        tooltip.style.left = `${containerWidth - originalRect.width - padding}px`;
    }
    if (positionedRect.bottom > containerHeight) // не влезла высота - выше курсора
    {
        tooltip.style.top = `${pointerY - originalRect.height - padding}px`;
    }
    tooltip.style.visibility = 'visible';
}

// excel-dashboard
window.InitSpreadsheet = function (id, fileBytes)
{
  const sheetContainer$ = $("#" + id).kendoSpreadsheet();
  const sheet           = sheetContainer$.data("kendoSpreadsheet");


  const fileBlob = new Blob([new Uint8Array(fileBytes)],
                            {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})

  sheet.fromFile(fileBlob);
}

window.DestroySpreadsheet = function (id)
{
  const sheet$ = $("#" + id);
  kendo.destroy(sheet$);
}


// telerik-reporting
window.trvEventHandlers = {
  ready: function ()
  {
    // у Telerik проблема с полями в темной теме, принудительно добавляем им нужный класс отображения
    // таймаут нужен, т.к. эти поля почему-то не сразу появляются
    setTimeout(function ()
               {
                 document.querySelectorAll('.trv-parameter-value > .k-input')
                         .forEach(el => el.classList.add('k-input-solid'))
               },
               500);
  }
}