allfree-angular-frontend / src / app / article-operations / create-article / create-article.component.ts
create-article.component.ts
Raw
import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {Article, NewArticleDTO} from 'src/app/models/models';
import {TokenStorageService} from 'src/app/_services/jwt-service/token-storage.service';
import {UserService} from 'src/app/_services/user-service/user.service';
import {ToastModule} from 'primeng/toast';
import {MessageService} from 'primeng/api';
import { PrimeNGConfig } from 'primeng/api';
import {ImageService} from '../../_services/firebase-service/image.service';
import ArticleFire from '../../models/imageDetails';
import {map} from 'rxjs/operators';
import {FileUpload} from '../../models/file-upload';
import {FileUploadService} from '../../_services/firebase-service/file-upload.service';
import {ArticlesService} from '../../_services/article-service/articles.service';
import {AngularFireList} from '@angular/fire/database';

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

  userId: number;
  articles: Array<Article>;
  articleToSave =  new Article("","","","","","");
  savedArticleId: number;
  newArticleRequest = new NewArticleDTO(1,new Array<Article>());
  images?: AngularFireList<FileUpload>;
  selectedFiles?: FileList;
  currentFileUpload?: FileUpload;
  percentage = 0;
// test fetch
  fileUploads?: any[];
  imagesForArticle?: any[];

  constructor(
    private router: Router,
    private tokenStorage: TokenStorageService,
    private userService: UserService,
    private articleService: ArticlesService,
    private messageService: MessageService,
    private primengConfig: PrimeNGConfig,
    private imageService: ImageService,
    private uploadService: FileUploadService
  ) {}

  ngOnInit(): void {
    this.primengConfig.ripple = true;
    this.userId = this.tokenStorage.getUser().userDetails.id;
    this.uploadService.getFiles(100).snapshotChanges().pipe(
      map(changes =>
        // store the key
        changes.map(c => ({ key: c.payload.key, ...c.payload.val() }))
      )
    ).subscribe(fileUploads => {
      this.fileUploads = fileUploads;
    });
  }
  selectFile(event: any): void {
    this.selectedFiles = event.target.files;
  }
  async onSubmit(): Promise<void> {
    this.newArticleRequest.userId = this.userId;
    this.articleToSave.status = "PENDING";
    this.newArticleRequest.userArticles.push(this.articleToSave);
    // console.log("userid",this.userId);
    // console.log("articleToBeSaved",this.articleToSave);
    // console.log("new article",this.newArticleRequest.userArticles[0]);

    let fullUser = await this.userService.addArticleToUser(this.newArticleRequest).toPromise();
    this.uploadAndFetchImages(fullUser.articles[fullUser.articles.length - 1 ].id);
    console.log("saved article ",fullUser.articles[fullUser.articles.length - 1 ]);
      // , error => console.log(error));
    // console.log("savedArticleId",this.savedArticleId );
    // this.uploadAndFetchImages(this.savedArticleId);
    // this.reloadPage();


    // ==================ASYNC  && AWAIT TEST  ==================

    // this.addWithPromise();
    // this.addWithAsync();
    this.showSuccess();
  }
  // ==================ASYNC  && AWAIT TEST  ==================
 additionPromiseResult;
  additionAsyncResult;
  addWithPromise() {
    this.resolveAfter2Seconds(20).then(data1 => {
      let result1 = <number>data1;
      this.resolveAfter2Seconds(30).then(data2 => {
        let result2 = <number>data2;
        this.additionPromiseResult = result1 + result2;
        console.log(`promise result: ${this.additionPromiseResult}`);
      });
    });
  }
  async addWithAsync() {
    const result1 = <number>await this.resolveAfter2Seconds(20);
    const result2 = <number>await this.resolveAfter2Seconds(30);
    this.additionAsyncResult = result1 + result2;
    console.log(`async result: ${this.additionAsyncResult}`);
  }
  resolveAfter2Seconds(x) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve(x);
      }, 2000);
    });
  }
  // ==================ASYNC  && AWAIT TEST  ==================
  backToUserArticles(){
    this.router.navigate(['user/articles']);
  }
  showSuccess() {
    this.messageService.add({severity:'success', summary: 'Success', detail: 'Articol salvat'});
  }
  async uploadAndFetchImages(savedArticleId: number) {
    this.upload(savedArticleId).then(() => {
      // this.fetchUrlForArticle(this.articles[this.articles.length -1].id).then(value => {
      //   this.articles[this.articles.length-1].photos = this.fileUploads[0].url;
      //   console.log(this.fileUploads[0].url, new Date());
      //   this.articleService.updateArticle( this.articles[this.articles.length-1]);
      // });
    })
 }
  async upload(articleId: number): Promise<void> {
      if (this.selectedFiles) {
        const file: File | null = this.selectedFiles.item(0);
        this.selectedFiles = undefined;
        if (file) {
          this.currentFileUpload = new FileUpload(file);
          this.currentFileUpload.userId = this.userId;
          this.currentFileUpload.articleId = articleId;
          this.percentage = await this.uploadService.pushFileToStorage(this.currentFileUpload).toPromise();
        }
      }
    // console.log(this.currentFileUpload);
  }
  //ORGIGINAL FUNCTION

  // upload(articleId: number): Promise<void> {
  //   return new Promise<void>((resolve => {
  //     if (this.selectedFiles) {
  //       const file: File | null = this.selectedFiles.item(0);
  //       this.selectedFiles = undefined;
  //       if (file) {
  //         this.currentFileUpload = new FileUpload(file);
  //         this.currentFileUpload.userId = this.userId;
  //         this.currentFileUpload.articleId = articleId;
  //         this.uploadService.pushFileToStorage(this.currentFileUpload).subscribe(percentage => {this.percentage = Math.round(percentage ? percentage : 0);
  //           },
  //           error => {
  //             console.log("here" + error);
  //           }
  //         );
  //       }
  //     }
  //       resolve();
  //     }));
  // }
  fetchUrlForArticle(articleId: number) {
    return new Promise<void>(resolve => {
      this.uploadService.getFiles(100).snapshotChanges().pipe(
        map(changes =>
          // store the key
          changes.map(c => ({key: c.payload.key, ...c.payload.val()})).filter( img => img.articleId == articleId)
        )
      ).subscribe(fileUploads => {
        this.imagesForArticle = fileUploads;
      });
      resolve();
    })
  }
  reloadPage(): void {
    window.location.reload();
  }
  // function f1() {
  //   return new Promise((resolve, reject) => {
  //     console.log('f1');
  //     resolve();
  //   });
  // }
  //
  // function f2() {
  //   console.log('f2');
  // }
  //
  // f1().then(res => f2());
}