allfree-angular-frontend / src / app / home / home.component.ts
home.component.ts
Raw
import {Component, OnInit} from '@angular/core';
import {UserService} from '../_services/user-service/user.service';
import {APIResponse, Article} from '../models/models';
import {Router} from '@angular/router';
import {MessageService} from 'primeng/api';
import {TokenStorageService} from '../_services/jwt-service/token-storage.service';
import {FileUploadService} from '../_services/firebase-service/file-upload.service';
import {delay} from 'rxjs/operators';
import {Subscription} from 'rxjs';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  FULL_HEART_URL = '../../assets/images/full_heart.png';
  // EMPTY_HEART_URL = "../../assets/images/empty_heart.png";
  EMPTY_HEART_URL = '../../assets/images/empty-2.png';
  favLogoType = this.EMPTY_HEART_URL;
  publicArticles: any;
  // urlsByArticleID = new Map<number, string>();
  favArticlesOfLoggedUser: Array<Article>;
  favoriteArticlesIDs: Array<number>;
  favoriteArticlesSub: Subscription;
  urlsByArticleID ? = new Map<number, string>();
  db?: Array<any>;

  constructor(private userService: UserService,
              private tokenStorage: TokenStorageService,
              private router: Router,
              private messageService: MessageService,
              private uploadService: FileUploadService) {
  }

  ngOnInit(): void {
    this.getPublicArticlesForLoggedUser();
    this.getUserFavoriteArticles();
    this.initializeDataFromFirebase();
    // console.log(this.publicArticles);
  }

  getUrl(articleId: number): string {
    return this.urlsByArticleID.get(articleId) ?? 'assets/images/image-placeholder.png';
  }

  getPublicArticlesForLoggedUser() {
    if (this.tokenStorage.getUser() == null) {
      this.showFail();
    } else {
      this.userService.getArticlesForLoggedUser().toPromise().then(
        val => {
          this.publicArticles = val;
        }
      ).finally(() => {
        console.log('getting articles done');
      });
      // this.userService.getArticlesForLoggedUser().subscribe(value => {
      //     this.publicArticles = value;
      //   },
      //   error => {
      //     console.log("getting articles for user",error);
      //   },
      //   () => {
      //     console.log("completed");
      //   });
    }
  }

  getUserFavoriteArticles() {
    this.favoriteArticlesSub = this.userService
      .getUserFavoriteArticles()
      .subscribe((articleList: APIResponse<Article>) => {
          this.favoriteArticlesIDs = articleList.results.map(value => value.id);
        },
        error => {
          console.log(error);
        },
        () => {
          console.log('fetch fav complete');
        });
    // console.log('Fav Articles => ', this.favoriteArticlesIDs);
  }

  // getUrl(articleId: number): string {
  //   return this.urlsByArticleID.get(articleId) ?? "../../assets/images/image-placeholder.png";
  // }

  initializeDataFromFirebase() {
    // this.uploadService.getFiles(100).valueChanges().toPromise().then(value => {
    //   this.db = value;
    // },
    //   err => {
    //     console.log(err);
    //   }).then(() => {
    //   console.log("then done");
    // }).finally(() => {
    //     // this.initializeMapWithURLs();
    //     console.log("init done");
    // })
    this.uploadService.getFiles(100).valueChanges()
      .subscribe(value => {
          this.db = value;
        },
        error => {
          console.log(error);
        },
        () => {
          console.log('fetch complete');
          // this.test();
        });
    // delay(1000);
    // this.initializeMapWithURLs();
  }

  test() {
    console.log('db fetch complete');
  }

  initializeMapWithURLs() {
    this.db.map(value => {
      this.urlsByArticleID.set(value.articleId, value.url);
    });
  }

  openArticleDetails(id) {
    this.router.navigate(['article-details/', id]);
  }

  heartLogoForArticle(articleId: number) {
    // return this.FULL_HEART_URL;
    if (this.favoriteArticlesIDs != undefined && this.favoriteArticlesIDs.includes(articleId)) {
      console.log(this.favoriteArticlesIDs.includes(articleId));
      return this.FULL_HEART_URL;
    } else {
      return this.FULL_HEART_URL;
    }
    this.getUserFavoriteArticles();
  }

  addToFav(id) {
    this.userService.addArticleToFav(id);
    this.favLogoType = this.FULL_HEART_URL;
    this.showSuccess();
  }

  showSuccess() {
    this.messageService.add({severity: 'success', summary: 'Success', detail: 'Adaugat la favorite'});
  }

  showFail() {
    this.messageService.add({severity: 'error', summary: 'Success', detail: 'Trebuie sa fii logat'});
  }

}