export const getFuelPrices = (pdv) => {
  const prices = []
  if (!pdv.children || pdv.children.length === 0) {
    return false;
  }
  for (let i = 0; i < pdv.children.length; i += 1) {
    const currentChildren = pdv.children[i];
    if (currentChildren.type === 'element' && currentChildren.name === 'prix') {
      prices.push({
        type: currentChildren.attributes.nom,
        price: parseInt(currentChildren.attributes.valeur, 10) / 1000,
        updatedAt: currentChildren.attributes.maj,
      });
    }
  }
  return prices;
};

export const getPlvInformation = (pdv, name) => {
  if (!pdv.children || pdv.children.length === 0) {
    return false;
  }
  for (let i = 0; i < pdv.children.length; i += 1) {
    const currentChildren = pdv.children[i];
    if (currentChildren.type === 'element' && currentChildren.name === name) {
      
      if ( currentChildren.children && currentChildren.children.length > 0 ) {
        return currentChildren.children[0].value;
      }

      return null;
    }
  }
  return false;
};

export const formatPosition = (value) => value / 100000;

export const haveSelectedGas = (station, gas) => {
  if (!station.prices || station.prices.length === 0 ) {
    return false;
  }

  for (let i = 0 ; i < station.prices.length ; i +=1 ){
    if (station.prices[i].type === gas ) {
      return true;
    }
  }
  return false; 
}

export const extractGasStationFromXml = (currentPdv ) => {
  return {
    id: currentPdv.attributes.id,
    latitude: formatPosition(currentPdv.attributes.latitude),
    longitude: formatPosition(currentPdv.attributes.longitude),
    prices: getFuelPrices(currentPdv),
    postCode: currentPdv.attributes.cp,
    address: getPlvInformation(currentPdv, 'adresse'),
    city: getPlvInformation(currentPdv, 'ville')
  }
}
 