import { tradeOptionToProposal } from '../tools'

export default Engine => class Proposal extends Engine {
  constructor() {
    super()
    this.expectedProposalCount = 0
  }
  makeProposals(tradeOption) {
    if (!this.isNewTradeOption(tradeOption)) {
      return
    }
    this.proposalTemplates = tradeOptionToProposal(tradeOption)
    this.unsubscribeProposals()
    this.requestProposals()
  }
  selectProposal(contractType) {
    let toBuy
    let toForget

    this.data.get('proposals').forEach(proposal => {
      if (proposal.contractType === contractType) {
        toBuy = proposal
      } else {
        toForget = proposal
      }
    })

    this.api.unsubscribeByID(toForget.id).then(() => this.requestProposals())

    return toBuy
  }
  requestProposals() {
    this.data = this.data.set('proposals', new Map())

    this.proposalTemplates.forEach(proposal => {
      this.api.subscribeToPriceForContractProposal(proposal).then(r => {
        this.data = this.data.setIn(['proposals', r.proposal.id],
          Object.assign({ contractType: proposal.contract_type }, r.proposal))
        this.setProposalCount()
      })
    })
  }
  observeProposals() {
    this.listen('proposal', r => {
      const proposal = r.proposal
      const id = proposal.id

      if (this.data.hasIn(['proposals', id])) {
        this.data.setIn(['proposals', id], proposal)
        this.setProposalCount()
      }
    })
  }
  unsubscribeProposals() {
    if (!this.data.has('proposals')) {
      return
    }
    this.data.get('proposals').forEach(proposal =>
      this.api.unsubscribeByID(proposal.id))
  }
  setProposalCount() {
    this.expectedProposalCount = (this.expectedProposalCount + 1) % 2
  }
  checkProposalReady() {
    return this.data.get('proposals').size && !this.expectedProposalCount
  }
  isNewTradeOption(tradeOption) {
    if (!this.tradeOption) {
      this.tradeOption = tradeOption
      return true
    }

    const isNotEqual = key => this.tradeOption[key] !== tradeOption[key]

    return (isNotEqual('duration') || isNotEqual('amount') ||
      isNotEqual('prediction') || isNotEqual('barrierOffset') ||
      isNotEqual('secondBarrierOffset'))
  }
}

@@ -1273,20 +1273,36 @@
 %0A%0A      
-if (
+const oldProposal = 
 this.dat
@@ -1303,19 +1303,19 @@
 is.data.
-has
+get
 In(%5B'pro
@@ -1327,16 +1327,39 @@
 s', id%5D)
+%0A%0A      if (oldProposal
 ) %7B%0A    
@@ -1396,16 +1396,57 @@
 s', id%5D,
+%0A          Object.assign(%7B%7D, oldProposal,
  proposa
@@ -1447,16 +1447,17 @@
 roposal)
+)
 %0A       

Fix contractType in updated proposals