<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) => loan.title = name"
  @del="del"
  @update:borrowerNum="(b) => estimate.borrower.num = b"
  @update:borrowerCredit="(c) => estimate.borrower.credit = c"
  @update:borrowerIncome="(m) => estimate.borrower.income = Math.round(m*100)"
  @update:transaction="(t) => estimate.transaction = t"
    @update:occupancy="(t) => estimate.occupancy = t"
  @update:price="setPrice"
  @update:property="(p) => estimate.property = p"

  @update:loanType="changeLoanType"
  @update:term="(lt) => loan.term = lt"
  @update:program="(p) => loan.program = p"
  @update:ltv="setLtv"
  @update:amount="setAmount"
  @update:housingDti="setHousingDti"
  @update:dti="setDti"
  @update:hoi="(hoi) => loan.hoi = Math.round(hoi*100)"
  @update:interest="(i) => loan.interest = i"
  @update:interestDays="(d) => loans[sel].interestDays = d"
  @update:hazardEscrow="(h) => loans[sel].hazardEscrow = h"
  @update:hazard="(h) => loan.hazard = Math.round(h * 100)"
  @update:taxEscrow="(t) => loans[sel].taxEscrow = t"
  @update:tax="(t) => loan.tax = Math.round(t*100)"
  @update:manualMI="perc => loan.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)
		hoi: 10000, // 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: "",
	occupancy: "",
	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 = Math.round(value*100)
	this.estimate.loans[this.sel].fees.forEach(fee => {
		if (fee.perc) fee.amount = Math.round(fee.perc * value)
	})
	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)
}

// 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) * 100
	if (!this.estimate.price) return

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

	this.loan.amount = Math.round(amount)
	let num = amount / this.estimate.price
	this.loan.ltv = Math.round(num*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 changeLoanType(id) {
    if (id == this.loan.type.id) return
    
    // Set mandatory upfront MIP in fees if type is FHA
    let i = this.loan.fees.findIndex(
            l => l.required && l.name == "FHA Upfront MIP"
        )
    if (id == 2) {
        this.loan.fees.push({
            amount: Math.round(this.estimate.price*1.75/100),
            perc: 1.75,
            name: "FHA Upfront MIP",
            type: "Required",
            id: 0,
            required: true
        })
    } else if (i >= 0) {
        this.loan.fees.splice(i, 1)
    }
    
    this.loan.type.id = id
}

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, changeLoanType
	},
	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>