<template>
<div id="new" class="page">

<h2>New Loan</h2>

<section class="loans-list">

<h3 v-for="(l, indx) in loans"
:class="sel == indx ? 'sel' : ''"
@click="() => sel = indx"
>
{{l.title}}
</h3>

<div class="add">
<svg @click="create"
xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
class="bi bi-plus" viewBox="0 0 16 16"> <path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0
0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"/> </svg>
</div>
</section>

<loan-details v-if="hash == '#new'"
  :estimate="estimate"
  :loans="estimate.loans"
  :sel="sel"
  :loan="loan"
  :token="token"
  
  @update:name="(name) => loans[sel].title = name"
  @del="del"
  @update:borrowerNum="(b) => estimate.borrower.num = b"
  @update:borrowerCredit="(c) => estimate.borrower.credit = c"
  @update:borrowerIncome="(m) => estimate.borrower.income = m"
  @update:transaction="(t) => estimate.transaction = t"
  @update:price="setPrice"
  @update:property="(p) => estimate.property = p"

  @update:loanType="(lt) => loan.type.id = lt"
  @update:term="(lt) => loans[sel].term = lt"
  @update:program="(p) => loans[sel].program = p"
  @update:ltv="setLtv"
  @update:amount="setAmount"
  @update:housingDti="setHousingDti"
  @update:dti="setDti"
  @update:hoa="(hoa) => loans[sel].hoa = hoa"
  @update:interest="(i) => loans[sel].interest = i"
  @update:interestDays="(d) => loans[sel].interestDays = d"
  @update:hazardEscrow="(h) => loans[sel].hazardEscrow = h"
  @update:hazard="(h) => loans[sel].hazard = h"
  @update:taxEscrow="(t) => loans[sel].taxEscrow = t"
  @update:tax="(t) => loans[sel].tax = t"
  @update:manualMI="perc => loans[sel].mi.rate = perc"
  @toggle:manualMIMonthly=
  "() => loans[sel].mi.monthly = !loans[sel].mi.monthly"
  @continue="generate"
/>
<loan-summary v-if="hash == '#new/summary'"
    :loan="loan" :downpayment="estimate.price - loan.amount" :token="token" :estimate="estimate"/>

</div>
</template>

<script>
import { stripLetters, strip, stripInt, stripPerc } from "../../helpers.js" 
import LoanDetails from "./details.vue"
import LoanSummary from "./summary.vue"

// The default values of a new loan
const example = {
		title: "Example",
		type: {},
		term: 0,
		ltv: 0, // Loan to home value ratio
		dti: 0,
		housingDti: 0,
		amount: 0,
		interest: 0,
		interestDays: 0,
		hazard: 0, // Hazard insurance monthly payment
		hazardEscrow: 0, // Hazard insurance escrow in months (0 is none)
		tax: 0, // Real Estate taxes monthly payment
		taxEscrow: 0, // Months to escrow (0 is none)
		hoa: 100, // Home owner's association monthly fee
		program: "",
		pud: true, // Property under development
		zip: '',
		fees: [],
		mi: { monthly: false, rate: 0 }
}

// The default loans on a new estimate
const loans = [
	Object.assign({mi: { monthly: false, rate: 0 }, type: {}}, example)
]

// Default estimate fields
const estimate = {
	property: "",
	transaction: 0,
	price: 0,
	borrower: {num: 0, credit: 0, income: 0},
	loans: loans,
}

function loan() {
    return this.estimate.loans[this.sel]
}

// Clone loan from initial example as a new loan
function create() {
	this.estimate.loans.push(
		Object.assign(
		    {mi: { monthly: false, rate: 0 }, type: {}},
		    example, {fees: this.createFees()}
		)
	)
}


function createFees() {
	return this.fees.map(f => Object.assign({}, f))
}


function del() {
	if (this.loans.length > 1) {
		let x = this.sel
		this.sel = 0
		this.loans.splice(x, 1)
	}
}

// Updates the property price for all loans and their fee amounts.
function setPrice(value) {
	this.estimate.price = value
	this.estimate.loans[this.sel].fees.forEach(fee => {
		if (fee.perc) fee.amount = (fee.perc / 100 * value).toFixed(2)
	})
	this.estimate.loans.forEach(l => {l.ltv = 0; l.amount = 0})
}


// Changes loan.ltv's <input> and data() values, then syncs with data.amount
function setLtv(e) {
	let ltv = strip(e)
	if (!this.estimate.price) return

	if (ltv > 100) ltv = 100
	if (ltv < 0) ltv = 0

	this.loan.ltv = ltv
	let num = ltv / 100 * this.estimate.price
	this.loan.amount = Math.round(num*100)
}

// Changes loan.amount\'s <input> and data() values, then syncs with data.ltv
// Loan amount is in cents but LTV is in decimals so some rounding needs to be done.
function setAmount(e) {
	let amount = strip(e)
	if (!this.estimate.price) return

	if (amount > this.loan.price) amount = this.loan.price
	if (amount < 0) amount = 0

	this.loan.amount = Math.round(amount * 100)
	let num = amount / this.estimate.price * 100
	this.loan.ltv = Math.round(num*100) / 100
}

function setDti(e) {
	let dti = strip(e)
	let loan = this.loans[this.sel]
	if (!loan.price) return

	if (dti > 100) dti = 100
	if (dti < 0) dti = 0

	e.target.value = dti
	loan.dti = dti
}

function setHousingDti(e) {
	let housingDti = strip(e)
	let loan = this.loans[this.sel]
	if (!loan.price) return

	if (housingDti > 100) housingDti = 100
	if (housingDti < 0) housingDti = 0

	e.target.value = housingDti
	loan.housingDti = housingDti
}

function generate() {
    window.location.hash = 'new/summary'
}
  
// Percentage values of fees always take precedent over amounts. The conversion
// happens in setPrice()
export default {
	components: { LoanSummary, LoanDetails },
	methods: {
		generate, createFees, del, create, setPrice, setLtv, setAmount,
		setDti, setHousingDti
	},
	computed: { loan },
	props: ['user', 'fees', 'token'],
	data() {
		return {
				estimate: estimate,
				loans: estimate.loans,
				sel: 0,
				errors: [],
				hash: window.location.hash
			}
	},
	created() {
		this.estimate.loans.forEach(l => l.fees = this.createFees())
		window.addEventListener("hashchange",
		() => this.hash = window.location.hash)
	}
}
</script>