import ResizeImage from './resize-image';

const parseQuery = (query) => {
  const s = query.split('&');
  const data = {};
  const iz = s.length;
  let i = 0;
  let param;
  let key;
  let value;

  for (; i < iz; i++) {
    param = s[i].split('=');
    if (param[0] !== undefined) {
      key = param[0];
      value = (param[1] !== undefined) ? param.slice(1).join('=') : key;
      try {
        data[key] = decodeURIComponent(value);
      } catch (e) {
        console.log(e);
      }
    }
  }
  return data;
};

const getParameterByName = (name, query) => {
  const search = query || location.search;
  name = name.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
  const regex = new RegExp(`[\\?&]${name}=([^&#]*)`);
  const results = regex.exec(search);
  try {
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  } catch (e) {
    return '';
  }
};

const addListener = (name, listener, dom) => {
  dom = dom || document;

  // non-IE
  if (dom.addEventListener) {
    dom.addEventListener(name, listener, false);
    // IE8
  } else if (dom.attachEvent) {
    dom.documentElement[name] = 0;
    dom.documentElement.attachEvent('onpropertychange', function (event) {
      if (event.propertyName === name) {
        listener();
        dom.documentElement.detachEvent('onpropertychange', arguments.callee);
      }
    });
  }
};

const dispatchEvent = (name, obj, dom) => {
  obj = obj || {};
  dom = dom || document;

  // non-IE
  if (document.createEvent) {
    const evn = document.createEvent('HTMLEvents');
    evn.obj = obj;
    evn.initEvent(name, true, false);
    dom.dispatchEvent(evn);
    // IE
  } else if (dom.createEventObject) {
    dom.documentElement[name]++;
  }
};

const acmsEval = (expr) => {
  Function(expr)();
};

const PerfectFormData = (dom, dataUrlClass) => {
  const clone = dom.cloneNode(true);

  // セレクトボックスの入力値の登録(cloneのbug対応)
  const selectors = dom.querySelectorAll('select');
  const cloneSelectors = clone.querySelectorAll('select');
  [].forEach.call(selectors, (select, i) => {
    [].forEach.call(select.options, (option, j) => {
      cloneSelectors[i].options[j].selected = select.options[j].selected;
    });
  });

  // input要素の削除とdataUrlの削除
  const inputs = clone.querySelectorAll('input');
  [].forEach.call(inputs, (input) => {
    if (input.getAttribute('type') === 'file' || input.classList.contains(dataUrlClass)) {
      input.remove();
    }
  });

  // DOMからFromDataを作成
  const formData = new FormData(clone);
  const postModule = dom.querySelector('[name^=ACMS_POST_]');
  formData.append(postModule.getAttribute('name'), postModule.value);

  // ファイル要素を追加
  const inputs2 = dom.querySelectorAll('input');
  [].forEach.call(inputs2, (input) => {
    if (input.getAttribute('type') === 'file') {
      const name = input.getAttribute('name');
      if (input.files.length > 0) {
        [].forEach.call(input.files, (file) => {
          formData.append(name, file);
        });
      } else {
        formData.append(name, new File([''], ''));
      }
    }
  });

  // dataUrlをblobに変換してFormDataに追加
  const base64Data = dom.querySelectorAll(`.${dataUrlClass}`);
  [].forEach.call(base64Data, (item) => {
    const dataUrl = item.value;
    if (!dataUrl) return;
    const name = item.getAttribute('name');
    const resizeImage = new ResizeImage();
    const blob = resizeImage.dataUrlToBlob(dataUrl);
    if (blob) {
      formData.append(name, blob);
    }
  });

  return formData;
};

export { parseQuery, getParameterByName, addListener, dispatchEvent, acmsEval, PerfectFormData };

