import { Parcel } from '../model/models'

export const splitWeightIntoParcels = (
  totalWeight: number,
  maxWeight: number | undefined
): Array<Parcel> => {
  let remainingWeight = totalWeight
  const parcels: Array<Parcel> = []

  if (maxWeight && totalWeight > maxWeight) {
    while (remainingWeight > 0) {
      if (remainingWeight > maxWeight) {
        parcels.push({ weightInGrams: 100 })
        remainingWeight -= maxWeight
      } else {
        parcels.push({ weightInGrams: 100 })
        remainingWeight = 0
      }
    }
  } else {
    parcels.push({
      weightInGrams: totalWeight !== 0 ? totalWeight : 100,
    })
  }
  return parcels.length ? parcels : [{ weightInGrams: 100 }]
}
