import { ContactAddress } from "./contact-address"; import { ContactParams } from "./contact-params"; export class ContactItem { public readonly data: ContactParams; public readonly id: string; public readonly hash: string; public addrs: ContactAddress[]; public groups: string[]; public names: string[]; public notes: string; public canSendFromAddrs: ContactAddress[]; constructor(props: ContactParams) { this.data = props; this.hash = props.hash; this.id = props.id; this.canSendFromAddrs = (props.canSendFromAddrs || []).map(addrString => ContactAddress.fromPrefixedString(addrString)); this.addrs = (props.addrs || []).map(addrString => ContactAddress.fromPrefixedString(addrString)); this.groups = props.groups || []; this.names = props.names || []; if (this.names.length === 0) { this.names.push(this.generateName()); } this.notes = props.notes || ''; } public matchesGroup(group: string): boolean { if (this.groups.filter(x => x === group.trim())[0].length > 0) { return true; } return false; } public getFirstEmail(): string | undefined { const first = this.addrs.filter(addr => addr.type === 'email')[0]; if (first == null) { return undefined; } return first.address; } public getFirstPhone(): string | undefined { const first = this.addrs.filter(addr => addr.type === 'phone')[0]; if (first == null) { return undefined; } return first.address; } public search(search: string): boolean { if (this.names.find(i => i.toLowerCase().trim().indexOf(search.toLowerCase().trim()) >= 0)) { return true; } if (this.addrs.find(addr => addr.matches(search))) { return true; } return false; } public getMatchingAddresses(search: string): ContactAddress[] { return this.addrs.filter(addr => addr.matches(search)); } public matchesAddressExactly(addressType: string, addressValue: string): boolean { if (this.addrs.find(addr => addr.matchesExactly(addressType, addressValue))) { return true; } return false; } public generateName() { const firstEmail = this.getFirstEmail(); if (firstEmail != null) { return firstEmail; } const firstPhone = this.getFirstPhone(); if (firstPhone != null) { return firstPhone; } return 'New contact ' + this.id.substring(0,8); } public getName(): string { if (this.names.length > 0) { return this.names[0]; } else { return ''; } } public getData(): ContactParams { return { addrs: this.addrs.map(addr => addr.toPrefixedString()), canSendFromAddrs: this.canSendFromAddrs.map(addr => addr.toPrefixedString()), groups: this.groups, hash: this.hash, id: this.id, names: this.names, notes: this.notes }; } }