import { Component , OnInit } from '@angular/core' ; import { Item } from '../../item' ; import { PosService } from '../../pos.service' ; import { DatabaseService } from '../../database.service' ; @ Component ( { selector : 'app-ticket' , templateUrl : './ticket.component.html' , styleUrls : [ './ticket.component.scss' ] } ) export class TicketComponent implements OnInit { ticket : Item [ ] = [ ] ; cartTotal = 0 ; cartNumItems = 0 ; constructor ( private ticketSync , private db ) { } ngOnInit ( ) { this . ticketSync . currentTicket . subscribe ( data => this . ticket = data ) ; this . ticketSync . currentTotal . subscribe ( total => this . cartTotal = total ) ; this . ticketSync . currentCartNum . subscribe ( num => this . cartNumItems = num ) ; } addItem ( item ) { if ( this . ticket . includes ( item ) ) { this . ticket [ this . ticket . indexOf ( item ) ] . quantity += 1 ; } else { this . ticket . push ( item ) ; } this . syncTicket ( ) ; this . calculateTotal ( ) ; } removeItem ( item ) { if ( this . ticket . includes ( item ) ) { const index = this . ticket . indexOf ( item ) ; if ( index > - 1 ) { this . ticket [ this . ticket . indexOf ( item ) ] . quantity = 1 ; this . ticket . splice ( index , 1 ) ; } } this . syncTicket ( ) ; this . calculateTotal ( ) ; } subtractOne ( item ) { if ( this . ticket [ this . ticket . indexOf ( item ) ] . quantity === 1 ) { this . removeItem ( item ) ; } else { this . ticket [ this . ticket . indexOf ( item ) ] . quantity = this . ticket [ this . ticket . indexOf ( item ) ] . quantity - 1 ; } this . syncTicket ( ) ; this . calculateTotal ( ) ; } calculateTotal ( ) { let total = 0 ; let cartitems = 0 ; this . ticket . forEach ( function ( item ) { total += ( item . price * item . quantity ) ; cartitems += item . quantity ; } ) ; this . cartTotal = total ; this . cartNumItems = cartitems ; this . ticketSync . updateNumItems ( this . cartNumItems ) ; this . ticketSync . updateTotal ( this . cartTotal ) ; } clearCart ( ) { this . ticket . forEach ( function ( item ) { item . quantity = 1 ; } ) ; this . ticket = [ ] ; this . syncTicket ( ) ; this . calculateTotal ( ) ; } syncTicket ( ) { this . ticketSync . changeTicket ( this . ticket ) ; } checkout ( ) { if ( this . ticket . length > 0 ) { this . db . pushOrder ( this . ticket , this . cartTotal , this . cartNumItems ) ; this . clearCart ( ) ; } } }