const _ = require('lodash');

const create = (positions) => {
  positions = setValuationProperties(positions);
  // positions = _.filter(positions, p => p.currentValue);

  const totalValue = getValue(positions);
  positions = setWeightedMarginOfSafety(positions, totalValue);
  const margin = getMargin(positions);

  return {
    positions,
    value: totalValue,
    margin,
  };
};

const setValuationProperties = (positions) => {
  return assignCurrentValue(positions);
};

const assignCurrentValue = (positions) => {
  return _.map(positions, (position) => {
    const price = _.get(position, 'stock.historicals.close');
    const amount = _.get(position, 'amount');

    position.currentValue = price * amount;

    return position;
  });
};

const getValue = (positions) => {
  return _.sumBy(positions, getCurrentValueBy);
};

const getCurrentValueBy = (position) => {
  if(isValidNumber(position.currentValue)) {
    return position.currentValue;
  }

  if(isValidNumber(position.value)) {
    return position.value;
  }

  return 0;
};

const isValidNumber = (value) => {
  return _.isNumber(value) && _.isNaN(value) === false;
};

const setWeightedMarginOfSafety = (positions, totalValue) => {
  return _.map(positions, (position) => {
    const value = position.currentValue || position.value || 0;

    position.stake = value / totalValue;

    const marginOfSafety = _.get(position, 'stock.margin') || 0;
    position.marginOfSafetyPortfolioWeight = position.stake * marginOfSafety;

    // console.log(position.ticker, position.stake, marginOfSafety, position.marginOfSafetyPortfolioWeight);

    return position;
  });
};

const getMargin = (positions) => {
  return _.meanBy(positions, (position) => {
    return position.marginOfSafetyPortfolioWeight;
  });
};

module.exports = {
  create,
};

@@ -150,22 +150,32 @@
  =%3E 
-p.currentValue
+_.get(p, 'stock.margin')
 );%0A%0A
@@ -229,32 +229,37 @@
 itions = set
+Stake
 Weighted
 MarginOfSafe
@@ -246,30 +246,26 @@
 Weighted
-MarginOfSafety
+Properties
 (positio
@@ -321,16 +321,247 @@
 ions);%0A%0A
+  const stake = _%0A    .chain(positions)%0A    .map('stake')%0A    .sum()%0A    .value();%0A%0A  const PE = _.meanBy(positions, (position) =%3E %7B return position.PE; %7D);%0A  const PB = _.meanBy(positions, (position) =%3E %7B return position.PB; %7D);%0A%0A
   return
@@ -605,18 +605,46 @@
 ue,%0A
-    margin
+%0A    stake,%0A    margin,%0A    PE,%0A    PB
 ,%0A  
@@ -1415,24 +1415,29 @@
 onst set
+Stake
 Weighted
 MarginOf
@@ -1432,22 +1432,18 @@
 hted
-MarginOfSafety
+Properties
  = (
@@ -1770,112 +1770,180 @@
 %0A   
- //
  cons
-ole.log(position.ticker, position.stake, marginOfSafety, position.marginOfSafetyPortfolioWeight)
+t PE = _.get(position, 'stock.PE') %7C%7C 0;%0A    position.PE = position.stake * PE;%0A%0A    const PB = _.get(position, 'stock.PB') %7C%7C 0;%0A    position.PB = position.stake * PB
 ;%0A%0A 

update portfolio