import * as React from "react" ; import * as ReactDOM from "react-dom" ; import * as MvcRouter from "mvc-router-spa" ; import { ControllerBase } from "./ControllerBase" ; import { AccountType , Account } from "../Models/Account" ; import { BankApp } from "../BankApp" ; import { MessageBox } from "../Dialogs/MessageBox" ; import * as Storage from "../Utils/Storage" ; import { TransactionPageProps , TransactionPage , TransactionPageState , TransactionPageLabels } from "../Views/TransactionPage" ; export class TransactionController extends ControllerBase { private accountType : number ; private depositing : boolean ; private account : Account ; private transactionPage : TransactionPage ; constructor ( app ) { super ( app ) ; } protected loadPage ( params ) { this . accountType = parseInt ( params [ "type" ] , 10 ) ; this . depositing = ( params [ "mode" ] === "deposit" ) ; const props = { labels : this . depositing ? depositLabels : withdrawalLabels , onOkClicked : ( ) => this . onOkClicked ( ) , onCancelClicked : ( ) => this . onCancelClicked ( ) , ref : component => { if ( component ) { this . transactionPage = component ; } } } ; ReactDOM . render ( React . createElement ( TransactionPage , props ) , this . pageContainer , ( ) => { this . initPage ( ) ; } ) ; } private initPage ( ) { this . account = this . app . getBank ( ) . getAccount ( this . accountType ) ; this . transactionPage . setState ( { accountName : this . account . getName ( ) , balance : this . account . getBalance ( ) } ) ; } private onOkClicked ( ) { if ( this . depositing ) { this . performDeposit ( ) ; } else { this . performWithdrawal ( ) ; } } private performDeposit ( ) { const amount = this . transactionPage . getAmount ( ) ; this . account . depositMoney ( amount ) ; Storage . store ( AccountType [ this . accountType ] , this . account . getBalance ( ) . toString ( ) ) ; this . transactionPage . setState ( { balance : this . account . getBalance ( ) } ) ; MessageBox . show ( "Amount deposited." ) . then ( ( ) => { this . app . navigate ( "/" ) ; } ) ; } private performWithdrawal ( ) { const amount = this . transactionPage . getAmount ( ) ; try { this . account . withdrawMoney ( amount ) ; Storage . store ( AccountType [ this . accountType ] , this . account . getBalance ( ) . toString ( ) ) ; this . transactionPage . setState ( { balance : this . account . getBalance ( ) } ) ; MessageBox . show ( "Amount withdrawn." ) . then ( ( ) => { this . app . navigate ( "/" ) ; } ) ; } catch ( ex ) { MessageBox . show ( ex . message ) ; } } private onCancelClicked ( ) { this . app . navigate ( `/account/${ this . accountType }` ) ; } } const depositLabels = { transactionType : "Deposit" , prompt : "How much do you want to deposit?" } ; const withdrawalLabels = { transactionType : "Withdrawal" , prompt : "How much do you want to withdraw?" } ;