aboutsummaryrefslogtreecommitdiff
path: root/src/content/usecases/FindUseCase.ts
blob: 88b516ce9e288c5a330ac5fa1596e22c2ca30f3e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { injectable, inject } from 'tsyringe';
import FindPresenter from '../presenters/FindPresenter';
import FindRepository from '../repositories/FindRepository';
import FindClient from '../client/FindClient';
import ConsoleClient from '../client/ConsoleClient';

@injectable()
export default class FindUseCase {
  constructor(
    @inject('FindPresenter') private presenter: FindPresenter,
    @inject('FindRepository') private repository: FindRepository,
    @inject('FindClient') private client: FindClient,
    @inject('ConsoleClient') private consoleClient: ConsoleClient,
  ) {
  }

  async startFind(keyword?: string): Promise<void> {
    this.presenter.clearSelection();
    if (keyword) {
      this.saveKeyword(keyword);
    } else {
      let lastKeyword = await this.getKeyword();
      if (!lastKeyword) {
        return this.showNoLastKeywordError();
      }
      this.saveKeyword(lastKeyword);
    }
    return this.findNext();
  }

  findNext(): Promise<void> {
    return this.findNextPrev(false);
  }

  findPrev(): Promise<void> {
    return this.findNextPrev(true);
  }

  private async findNextPrev(
    backwards: boolean,
  ): Promise<void> {
    let keyword = await this.getKeyword();
    if (!keyword) {
      return this.showNoLastKeywordError();
    }
    let found = this.presenter.find(keyword, backwards);
    if (found) {
      this.consoleClient.info('Pattern found: ' + keyword);
    } else {
      this.consoleClient.error('Pattern not found: ' + keyword);
    }
  }

  private async getKeyword(): Promise<string | null> {
    let keyword = this.repository.getLastKeyword();
    if (!keyword) {
      keyword = await this.client.getGlobalLastKeyword();
    }
    return keyword;
  }

  private async saveKeyword(keyword: string): Promise<void> {
    this.repository.setLastKeyword(keyword);
    await this.client.setGlobalLastKeyword(keyword);
  }

  private async showNoLastKeywordError(): Promise<void> {
    await this.consoleClient.error('No previous search keywords');
  }
}