317 lines
11 KiB
TypeScript

import { Type, Component, OnInit, ViewChild } from '@angular/core';
import { Loading, LoadingController, ModalController, NavParams, AlertController, MenuController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { StrongsModal } from '../../components/strongs-modal/strongs-modal';
import { PagesService } from '../../services/pages-service';
import { ProfileService, User } from './../../services/profile-service';
import { Reference } from '../../libs/Reference';
import { VersePickerModal } from '../../components/verse-picker/verse-picker';
import { AutoCompleteComponent } from 'ionic2-auto-complete';
import { SearchAutoCompleteService } from '../../services/search-autocomplete-service';
@Component({
templateUrl: 'search.html',
providers: [SearchAutoCompleteService]
})
export class SearchPage implements OnInit {
searchQuery = '';
loader: Loading;
@ViewChild('searchbar')
searchbar: AutoCompleteComponent;
constructor(
private pagesService: PagesService
, private alertCtrl: AlertController
, private menu: MenuController
, public loadingCtrl: LoadingController
, public modalCtrl: ModalController
, public profileService: ProfileService
, public params: NavParams
, public autocompleteService: SearchAutoCompleteService
) {
}
ngOnInit(): void {
if (this.profileService.localIsLoaded) {
this.loader = this.loadingCtrl.create({ content: 'Loading Page...' });
this.loader.present().then(() => {
let t = this.profileService.profile();
this.initializeItems(t);
this.loader.dismiss();
});
}
else {
this.profileService.onLocalStorageLoaded.subscribe(t => {
// Check if there is a profile saved in local storage
this.loader = this.loadingCtrl.create({ content: 'Loading Page...' });
this.loader.present().then(() => {
this.initializeItems(t);
this.loader.dismiss();
this.pagesService.initializePages(this.profileService.profile().saved_pages);
});
});
this.profileService.onSavedPagesChanged.subscribe(sp => {
this.pagesService.initializePages(sp);
});
}
}
initializeItems(u: User) {
// migrate old way of storing card items to the new.
let has_migrated = false;
for (let i in u.items) {
if (u.items.hasOwnProperty(i)) {
let ci = u.items[i];
if (ci['data'] !== undefined) {
if (ci['data'].qry !== undefined)
u.items[i] = { qry: ci['data'].qry, dict: ci.dict, type: ci.type };
else if (ci['data'].ref !== undefined)
u.items[i] = { qry: ci['data'].ref, dict: ci.dict, type: ci.type };
else if (ci['data'].word !== undefined)
u.items[i] = { qry: ci['data'].word, dict: ci.dict, type: ci.type };
else if (ci['data'].sn !== undefined)
u.items[i] = {
qry: ci['data'].sn,
dict: ci['prefix'] === 'G' ? 'grk' : 'heb',
type: ci.type
};
has_migrated = true;
}
}
}
for (let pg of u.saved_pages) {
for (let i in pg.queries) {
if (pg.queries.hasOwnProperty(i)) {
let ci = pg.queries[i];
if (ci['data'] !== undefined) {
if (ci['data'].qry !== undefined)
pg.queries[i] = { qry: ci['data'].qry, dict: ci.dict, type: ci.type };
else if (ci['data'].ref !== undefined)
pg.queries[i] = { qry: ci['data'].ref, dict: ci.dict, type: ci.type };
else if (ci['data'].word !== undefined)
pg.queries[i] = { qry: ci['data'].word, dict: ci.dict, type: ci.type };
else if (ci['data'].sn !== undefined)
pg.queries[i] = {
qry: ci['data'].sn,
dict: ci['prefix'] === 'G' ? 'grk' : 'heb',
type: ci.type
};
has_migrated = true;
}
}
}
}
// initialize the pages.
this.pagesService.initializePages(u.saved_pages);
this.profileService.save(); // save the new items list
if (this.params.data.queries !== undefined)
this.profileService.profile().items = JSON.parse(JSON.stringify(this.params.data.queries));
if (this.params.data.title === undefined)
this.profileService.title = 'Search';
else
this.profileService.title = this.params.data.title;
if (has_migrated)
this.profileService.save();
if (this.profileService.profile().items === undefined) {
this.profileService.profile().items = []; // sometimes, maybe because of all the weirdness with the remote syncing, this gets set to undefined, and it needs to be reset.
}
}
textSizeChanged() {
this.profileService.textSizeChanged();
this.profileService.localSave();
}
fontFamilyChanged() {
this.profileService.fontFamilyChanged();
this.profileService.localSave();
}
actionsMenu() {
this.menu.open('actions');
}
addPage() {
const alert = this.alertCtrl.create({
title: 'Save Search as Page',
inputs: [
{
name: 'title',
placeholder: 'Page Title'
}
],
buttons: [
{
text: 'Cancel',
role: 'cancel',
handler: (): void => {
console.log('Cancel clicked');
}
},
{
text: 'Save',
handler: data => {
const p = { queries: this.profileService.profile().items.slice(), title: data.title };
this.profileService.profile().saved_pages.push(p);
this.profileService.save();
this.pagesService.addPage(p);
}
}
]
});
alert.present();
}
updatePage() {
const page = this.profileService.profile().saved_pages.find(
i =>
i.title === this.params.data.title
);
page.queries = this.profileService.profile().items.slice();
this.profileService.save();
}
itemSelected(autocomplete: string) {
let qry = autocomplete;
let idx = qry.lastIndexOf(';');
let prefix = '';
let words = [];
if (idx > -1) {
qry = autocomplete.substr(idx + 1).trim();
prefix = autocomplete.substr(0, idx).trim() + '; ';
}
if (qry.startsWith('Book:')) {
this.searchQuery = prefix + qry.substr(qry.indexOf('Book:')+5).trim();
autocomplete = this.searchQuery;
}
else {
this.searchQuery = autocomplete;
}
}
setQuery(searchbar) {
this.searchQuery = searchbar.target.value;
}
getQuery(searchbar) {
this.updateUIwithItems(this.searchQuery, true);
}
isError(t: string) {
return t === 'Error';
}
isPassage(t: string) {
return t === 'Passage';
}
isStrongs(t: string) {
return t === 'Strongs';
}
isWords(t: string) {
return t === 'Words';
}
versePicker() {
const modal = this.modalCtrl.create(VersePickerModal, { onItemClicked: this });
modal.present();
}
getItemsNextToCard(data: OpenData) {
this.profileService.last = data.card;
this.updateUIwithItems(data.qry, data.from_search_bar);
}
getItemList(search: string): Promise<CardItem[]> {
this.searchbar.hideItemList();
return new Promise((resolve) => {
const list: CardItem[] = [];
try {
const qs = search.split(';');
for (let x in qs) {
if (qs.hasOwnProperty(x)) {
let q = qs[x].trim();
if (q !== '') {
// its a search term.
if (q.search(/[0-9]/i) === -1)
list.push({ qry: q, dict: 'na', type: 'Words' });
else if (q.search(/(H|G)[0-9]/i) !== -1) {
// its a strongs lookup
let dict = q.substring(0, 1);
if (dict.search(/h/i) !== -1)
dict = 'heb';
else
dict = 'grk';
q = q.substring(1, q.length);
list.push({ qry: q, dict: dict, type: 'Strongs' });
}
else {
// its a verse reference.
if (q.trim() !== '') {
const myref = new Reference(q.trim());
list.push({ qry: myref.toString(), dict: myref.Section.start.book.book_number > 39 ? 'G' : 'H', type: 'Passage' });
}
}
}
}
}
if (this.profileService.profile().clear_search_after_query)
$('.searchbar-input').val('');
this.profileService.save();
}
catch (error) {
list.push({ qry: error, type: 'Error', dict: 'na' });
console.log(error);
}
resolve(list);
});
}
updateUIwithItems(search: string, from_search_bar: boolean) {
this.getItemList(search).then(lst => {
this.loader = this.loadingCtrl.create({ content: 'Looking up Query...' });
this.loader.present().then(
() => {
for (let item of lst) {
if (item.type === 'Strongs' && this.profileService.profile().strongs_modal && !from_search_bar) {
const modal = this.modalCtrl.create(StrongsModal, { sn: parseInt(item.qry), dict: item.dict, onItemClicked: this });
modal.present();
} else
this.profileService.addItemToList(item);
}
this.loader.dismiss();
}
);
});
}
}
export type OpenData = { card: CardItem, qry: string, from_search_bar: boolean }
export type CardItem = { qry: string, type: string, dict: string }
class Item {
id: number;
data: any;
type: Type<any>;
dict: string;
}