aboutsummaryrefslogtreecommitdiff
path: root/src/app/components/post-page/post-page.component.ts
blob: 1ac89f44a46baec4ba3005cd77c10aee018a51eb (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { Title } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { Guid } from 'guid-typescript';
import { CommentService } from 'src/app/services/comment.service';
import { PostService } from 'src/app/services/post.service';
import { TokenService } from 'src/app/services/token.service';
import { Post } from 'src/models/post';
import { CloudinaryService } from 'src/app/services/cloudinary.service';

@Component({
  selector: 'app-post-page',
  templateUrl: './post-page.component.html',
  styleUrls: ['./post-page.component.css']
})
export class PostPageComponent implements OnInit {
  private _title = 'Post';
  public dataArrived = false;
  public loggedIn = false;
  public editable = false;
  public editingPost = false;
  public postId: Guid;
  public post: Post;
  public files: File[];
  public editPostFormGroup: FormGroup;
  public addCommentFormGroup: FormGroup;

  constructor(private _titleService: Title, private _router: Router, private _fb: FormBuilder, private _tokenService: TokenService, private _postService: PostService, private _commentService: CommentService, private _cloudinaryService: CloudinaryService){
    this._titleService.setTitle(this._title);
  }

  ngOnInit(): void {
    this.loggedIn = this._tokenService.getTokenFromSessionStorage() !== '';
    this.postId = Guid.parse(this._router.url.substring(6));
    this.files = [];

    // Gets the post and the logged in user and compares them,
    // to determine if the current post is made by the user
    this._postService.getPostRequest(this.postId).subscribe(
      (result: object) => {
        this.post = result as Post;
        this.post.fileURLs = Object.values(result)[7];
        if (this.loggedIn) {
          this.editable = this.post.creatorUsername === this._tokenService.getUsernameFromSessionStorageToken();
          this.editPostFormGroup.get('newPostMessage')?.setValue(this.post.message);
        }
        if (this.post.fileURLs.length > 0) {
          this.loadFiles();
        }
        else {
          this.dataArrived = true;
        }
      },
      () => {
        this._router.navigate(['/not-found']);
      }
    );

    this.editPostFormGroup = this._fb.group({
      newPostMessage: new FormControl(''),
      fileUpload: new FormControl('')
    });

    this.addCommentFormGroup = this._fb.group({
      newComment: new FormControl('')
    });
  }

  private loadFiles(): void {
    for (const fileURL of this.post.fileURLs) {
      this._cloudinaryService.getFileRequest(fileURL).subscribe(
        (result: object) => {
          const file = result as File;
          const tmp = {
            name: fileURL.match('(?<=\/)(?:.(?!\/))+$')?.pop() ?? 'Attachment'
          };

          Object.assign(file, tmp);
          this.files.push(file);

          if (this.files.length === this.post.fileURLs.length) {
            this.dataArrived = true;
          }
        }
      );
    }
  }

  backToFeed(): void {
    this._router.navigate(['/']);
  }

  backToProfile(): void {
    this._router.navigate(['/profile/' + this._tokenService.getUsernameFromSessionStorageToken()]);
  }

  toLogin(): void {
    this._router.navigate(['/login']);
  }

  onFileUpload(event: any): void {
    this.files.push(...event.target.files);
    this.editPostFormGroup.get('fileUpload')?.reset();
  }

  removeAttachment(fileName: string): void {
    this.files = this.files.filter(x => x.name !== fileName);
  }

  editPost(): void {
    if (this._tokenService.getTokenFromSessionStorage() === '') {
      this.toLogin();
      return;
    }

    if (this.editingPost) {
      const newMessage = this.editPostFormGroup.get('newPostMessage')?.value;

      if (newMessage === '' && newMessage !== this.post.message) {
        this._postService.putPostWithSessionStorageRequest(this.postId, newMessage, this.files).subscribe(
          () => {
            this.reloadPage();
          }
        );
        this.dataArrived = false;
      }
    }
    this.editingPost = !this.editingPost;
  }

  addComment(): void {
    if (!this.loggedIn) {
      this._router.navigate(['/login']);
      return;
    }

    const newComment = this.addCommentFormGroup.get('newComment')?.value;
    if (newComment !== '' && newComment !== null) {
      this._commentService.createCommentWithSessionStorageRequest(this.postId, newComment).subscribe(
        () => {
          this.editPostFormGroup.reset();
          this.reloadPage();
        }
      );
    }
  }

  deletePost(): void {
    this._postService.deletePostWithSessionStorage(this.postId).subscribe(
      () => {
        this._router.navigate(['/profile/' + this._tokenService.getUsernameFromSessionStorageToken()]);
      }
    );
  }

  private reloadPage(): void {
    this._router.routeReuseStrategy.shouldReuseRoute = () => false;
    this._router.onSameUrlNavigation = 'reload';
    this._router.navigate([this._router.url]);
  }
}