import React from 'react';
import * as Constants from './constants';
import Modal from './components/UI/Modal/Modal';
import axios from 'axios';

const ipcRenderer = (!process.versions.hasOwnProperty('electron') && window && window.require) ?
  window.require('electron').ipcRenderer :
  null;

export const checkNewReleases = selectedVersion => {
  let previousReleases = localStorage.getItem('previous_releases');
  if (previousReleases) {
    previousReleases = JSON.parse(previousReleases).VersionLookup;

    let currentReleases = localStorage.getItem('releases');
    if (currentReleases) {
      currentReleases = JSON.parse(currentReleases).VersionLookup;
      return getNewReleases(previousReleases, currentReleases, selectedVersion);
    }
  }

  return [];
};

export const createModalConditionally = (condition, jsx, critical, disableFocusTrap, transparent) => {
  const modalProps = {critical: critical, disableFocusTrap: disableFocusTrap, transparent: transparent};
  return condition ? (<Modal {...modalProps}>{jsx}</Modal>) : null;
};

export const extractFileNameFromURL = url => {
  const parts = url.split('/');
  return parts[parts.length - 1];
};

export const formatLinesForDisplay = lines => {
  let msg = '';
  for (let i = 1; i < lines.length; i++) {
    if (i > 1) {
      msg += '\n';
    }
    msg += (lines[i].replace(/(\\#)/gm, '#') + '\n');
  }
  return msg;
};

export const getChangesForRepertoryVersion = version => {
  return new Promise((resolve, reject) => {
    const url = `https://bitbucket.org/blockstorage/repertory/raw/${version}/CHANGELOG.md`;
    axios
    .get(url, {
      responseType: 'text',
    })
    .then(response => {
      try {
        let found = false;
        let ended = false;
        let lines = response.data
        .replace(/(\r\n)/gm, '\n')
        .split('\n')
        .filter(l => {
          return !ended && (l.length > 0) && (found
            ? !(ended = l.startsWith('## '))
            : (found = l.startsWith(`## ${version}`)));
        });
        resolve(lines);
      } catch (e) {
        reject(e);
      }
    })
    .catch(error => {
      reject(error);
    });
  });
};

export const getIPCRenderer = () => {
  return ipcRenderer;
};

export const getNewReleases = (existingLocations, newLocations, selectedVersion) => {
  const ret = [];
  if (existingLocations && newLocations) {
    Constants.RELEASE_TYPES.forEach(release => {
      newLocations[release]
      .filter(version => (version !== selectedVersion) && !existingLocations[release].includes(version) && (version !== 'unavailable'))
      .forEach(version => {
        ret.splice(0, 0, {
          Display: version,
          Release: Constants.RELEASE_TYPES.indexOf(release),
          Version: newLocations[release].indexOf(version),
          VersionString: version,
        });
      });
    });
  }

  return ret;
};

export const getSelectedVersionFromState = state => {
  return (state.relver.Version === -1) ?
    'unavailable' :
    state.relver.VersionLookup[Constants.RELEASE_TYPES[state.relver.Release]][state.relver.Version];
};

