import '../lib/polyfill';

import React from 'react';
import { render } from 'react-dom';
import Atable from 'a-table';
import PerfectScrollbar from 'perfect-scrollbar';
import 'perfect-scrollbar/css/perfect-scrollbar.css';

import { hasClass, addClass } from '../lib/dom';
import select2 from '../lib/select2';
import NavigationEdit from '../components/navigation-edit.js';
import QuickSearch from '../components/quick-search';
import DispatchLiteEditor, { DispatchLiteEditorField } from '../admin/lite-editor';
import DispatchSystemUpdate from '../admin/system-update';
import DispatchStaticExport from '../admin/static-export';
import DispatchColorPicker from '../admin/color-picker';
import RelatedEntries from '../components/related-entries';

const Entities = require('html-entities').AllHtmlEntities;

ACMS.Ready(() => {
  /**
   * Delayed contents event
   */
  ACMS.addListener('acmsAdminSelectTab', (e) => {
    ACMS.dispatchEvent('acmsAdminDelayedContents', e.target, e.obj);
  });
  ACMS.addListener('acmsAdminShowTabPanel', (e) => {
    ACMS.dispatchEvent('acmsAdminDelayedContents', e.target, e.obj);
  });
  ACMS.addListener('acmsDialogOpened', (e) => {
    ACMS.dispatchEvent('acmsAdminDelayedContents', e.target, e.obj);
  });

  /**
   * メニューのスクロールバー（IE以外）
   */
  if (!/^ie/.test(ACMS.Dispatch.Utility.getBrowser())) {
    const psDom = document.querySelector('.js-scroll-contents');
    if (psDom) {
      const ps = new PerfectScrollbar(psDom, {
        wheelSpeed: 1,
        wheelPropagation: true,
        minScrollbarLength: 20
      });
      ps.update();
    }
  }

  /**
   * マルチドメインの時は、target="_blank" を削除
   */
  if (ACMS.Config.multiDomain === '1') {
    const blankItems = document.querySelectorAll('[target=_blank],[target=_brank]');
    [].forEach.call(blankItems, (item) => {
      item.removeAttribute('target');
    });
  }

  /**
   * Color picker（IE10以上）
   */
  if (ACMS.Dispatch.Utility.browser().ltIE9) {
    const buttons = document.querySelectorAll('.js-acms-color-picker-submit');
    [].forEach.call(buttons, (button) => {
      button.parentNode.removeChild(button);
    });
  } else {
    DispatchColorPicker();
    ACMS.addListener('acmsAdminDelayedContents', () => {
      DispatchColorPicker();
    });
  }

  /**
   * クイックサーチ（IE10以上）
   */
  if (ACMS.Dispatch.Utility.browser().ltIE9 || ACMS.Config.auth === 'subscriber') {
    const buttons = document.querySelectorAll('.js-search-everything');
    [].forEach.call(buttons, (button) => {
      button.parentNode.removeChild(button);
    });
  } else if (ACMS.Config.quickSearchFeature === true) {
    document.body.insertAdjacentHTML('beforeend', "<div id='acms-search-everything'></div>");
    const quickSearch = document.querySelector('#acms-search-everything');
    render(<QuickSearch />, quickSearch);
  }

  /**
   * 擬似フォーム
   */
  const dispatchFakeForms = () => {
    const fakeForms = document.querySelectorAll('.js-fake-form');
    [].forEach.call(fakeForms, (item) => {
      const submit = item.querySelector('.js-submit');
      $(submit).unbind('click').bind('click', (e) => {
        e.preventDefault();
        const confirmMsg = $(submit).data('confirm');

        if (confirmMsg && !window.confirm(confirmMsg)) {
          return false;
        }

        const method = item.getAttribute('data-method');
        const form = document.createElement('form');

        form.setAttribute('method', method);
        form.style.display = 'none';

        $(item).find(':input, :radio, :checkbox, :submit').each((i, elm) => {
          const copy = elm.cloneNode(true);
          copy.value = elm.value;
          form.appendChild(copy);
        });
        document.body.appendChild(form);
        form.submit();
      });
    });
    $('form').submit(function () {
      $(this).find('.js-fake-form').remove();
    });
  };
  ACMS.addListener('acmsAdminDelayedContents', () => {
    dispatchFakeForms();
  });
  dispatchFakeForms();


  /**
   * System update
   */
  DispatchSystemUpdate();

  /**
   * Static export
   */
  DispatchStaticExport();


  /**
   * 固定ナビゲーション
   */
  const scrollAreaHeight = $('.js-scroll-fixed').height();
  $('.js-scroll-contents').css('padding-bottom', scrollAreaHeight);

  /**
   * Password strength checker
   */
  const passwordStrength = document.querySelectorAll(ACMS.Config.passwordStrengthMark);
  if (passwordStrength.length > 0) {
    const loader = new ACMS.SyncLoader();
    loader.next(`${ACMS.Config.jsRoot}dest/zxcvbn.js`).load(() => {
      [].forEach.call(passwordStrength, (item) => {
        ACMS.Admin.zxcvbn(item);
      });
    });
  }

  /**
   * Select2
   */
  const dispatchSelect2 = (elm) => {
    const target = elm || document;
    const selectBox = target.querySelectorAll(ACMS.Config.select2Mark);
    [].forEach.call(selectBox, (item) => {
      const option = {
        containerCssClass: 'acms-admin-selectbox',
        dropdownCssClass: 'acms-admin-select-dropdown',
      };
      if (item.querySelectorAll('option').length >= ACMS.Config.select2Threshold) {
        select2(item, option);
      }
    });
  };
  dispatchSelect2(document);
  ACMS.addListener('acmsAdminDelayedContents', (e) => {
    dispatchSelect2(e.target);
  });

  /**
   * Disclose password
   */
  const disclosePassword = document.querySelectorAll('.js-disclose_password');
  [].forEach.call(disclosePassword, (item) => {
    item.addEventListener('change', (event) => {
      const selector = event.target.getAttribute('data-target');
      const target = document.querySelector(selector);
      if (event.target.checked) {
        target.setAttribute('type', 'text');
      } else {
        target.setAttribute('type', 'password');
      }
    });
  });


  /**
   * Navigation editor
   */
  const dispatchNavigationEditor = (elm) => {
    const navigationEditor = elm.querySelector(ACMS.Config.navigationEditMark);
    if (navigationEditor && !/^ie/.test(ACMS.Dispatch.Utility.getBrowser())) {
      $('.js-navigation-ie').remove();
      const json = document.querySelector('#js-navigation-json');
      const items = JSON.parse(json.innerHTML);
      const entities = new Entities();
      items.forEach((item) => {
        item.navigation_attr = entities.decode(item.navigation_attr);
        item.navigation_a_attr = entities.decode(item.navigation_a_attr);
        item.navigation_label = entities.decode(item.navigation_label);
      });
      render(
        <NavigationEdit
          items={items}
          message={ACMS.Config.navigationMessage
          }
        />,
        navigationEditor
      );
    } else {
      $('.js-navigation-ie').show();
    }
  };
  dispatchNavigationEditor(document);
  ACMS.addListener('acmsAdminDelayedContents', () => {
    dispatchNavigationEditor(document);
  });

  /**
   * Table Editor
   */
  const dispatchAtable = (item) => {
    if (!item) {
      return;
    }
    const editor = item.querySelectorAll(`${ACMS.Config.aTableMark}:not(.editing)`);
    [].forEach.call(editor, (box) => {
      const dest = box.querySelector(ACMS.Config.aTableDestMark);
      const elem = box.querySelector('table');
      if (!elem) {
        return;
      }
      const table = new Atable(elem, {
        mark: ACMS.Config.aTableConf,
        selector: {
          option: ACMS.Config.aTableSelector
        },
        tableOption: ACMS.Config.aTableOption,
        message: ACMS.Config.aTableMessage
      });
      table.afterRendered = () => {
        dest.value = table.getTable();
      };
      table.afterEntered = () => {
        dest.value = table.getTable();
      };
      table.afterRendered();
      box.className += ' editing';
    });
  };

  /**
   * a-table
   */
  const dispatchATableField = (ctx) => {
    const tables = ctx.querySelectorAll(ACMS.Config.aTableFieldMark);
    [].forEach.call(tables, (table) => {
      dispatchAtable(table);
    });
  };
  dispatchATableField(document);
  ACMS.addListener('acmsAdminDelayedContents', () => {
    dispatchATableField(document);
  });

  /**
   * ユニット追加時のdispatch
   */
  ACMS.addListener('acmsAddUnit', (event) => {
    dispatchAtable(event.obj.item);
  });


  const dispatchRelatedEntrySearch = () => {
    const relatedEntry = document.querySelector('#relatedEntry');
    if (relatedEntry) {
      if (hasClass(relatedEntry, 'js-related-entry-ready')) {
        return;
      }
      addClass(relatedEntry, 'js-related-entry-ready');
      const items = [];
      $('.js-related_entry_item').each((i, item) => {
        items.push({
          id: $(item).data('id'),
          title: $(item).data('title'),
          categoryName: $(item).data('category-name'),
          url: $(item).data('url')
        });
      });
      render(<RelatedEntries items={items} />, relatedEntry);
    }
  };
  dispatchRelatedEntrySearch();
  ACMS.addListener('acmsAdminDelayedContents', () => {
    dispatchRelatedEntrySearch();
  });

  /**
   * Lite Editor
   */
  DispatchLiteEditor();
  ACMS.addListener('acmsAdminDelayedContents', () => {
    DispatchLiteEditorField();
  });
  ACMS.dispatchEvent('acmsAdminReady');

  /**
   * スタイルガイド
   */
  if ($('.js-navSubOpener').length > 0) {
    $('.js-navSubOpener').click(() => {
      $('.navSubGroup').toggleClass('acms-admin-block');
      return false;
    });

    const calcHeight = () => {
      const adminNav = $('.acms-navbar-admin').height() + 40;
      const height = $(window).height() - adminNav;
      $('.navSubGroup').height(`${height}px`);
    };

    calcHeight();

    $(window).resize(calcHeight);

    $('.js-sample-start').click(function () {
      $(this).parent().parent().toggleClass('active');
    });
  }
});

