import { HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Attachment } from './model/Attachment.model';
import { MatSnackBar } from '@angular/material/snack-bar';
import { LoadingService } from 'src/app/core/loading.service';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { finalize } from 'rxjs/operators';
import { New } from './model/New.model';
import { NewsFeatureState } from './store/news.reducers';
import { Store } from '@ngrx/store';
import { AddNewsAction, RemoveNewAction, SaveNewAction } from './store/news.actions';
import { bloomFindPossibleInjector } from '@angular/core/src/render3/di';

@Injectable({
  providedIn: 'root'
})
export class NewsService {

  constructor(
    private http: HttpClient, 
    private loadingService: LoadingService, 
    private store: Store<NewsFeatureState>,
    private snackBar: MatSnackBar
  ) { }

  private fetching: boolean = false;

  getNewsBatch(fromId?: number){
    if (!this.fetching){
      this.fetching = true;
      this.loadingService.enableLoading();
      this.http.get('/tadis/news/' + (fromId ? fromId : -1)).pipe(
        finalize(() => { this.loadingService.disableLoading(); })
      ).subscribe(
        (news: New[]) => {
          this.fetching = false;
          this.store.dispatch(new AddNewsAction(news));
        }
      );
    }
  }

  saveNew(newItem: New){
    this.loadingService.enableLoading();
    this.http.put('/tadis/news', newItem).pipe(
      finalize(() => { this.loadingService.disableLoading(); })
    ).subscribe(
      (newItem: New) => { 
        this.snackBar.open('Novinka úspěšně uložena.', 'zavřít', { duration: 2500 });
        this.store.dispatch(new SaveNewAction(newItem)); 
      }
    );
  }

  deleteNew(id: number){
    this.loadingService.enableLoading();
    this.http.delete('/tadis/news/' + id).pipe(
      finalize(() => { this.loadingService.disableLoading(); })
    ).subscribe(
      () => { 
        this.snackBar.open('Novinka úspěšně smazána.', 'zavřít', { duration: 2500 });
        this.store.dispatch(new RemoveNewAction(id)); 
      }
    );
  }

  getAttachment(attachment: Attachment){
    this.loadingService.enableLoading();
    this.http.get('/tadis/news/attachment/'+attachment.id, { responseType: 'blob' }).pipe(
      finalize(() => { this.loadingService.disableLoading(); })
    ).subscribe(
      (blob: Blob) => { 
        var downloadURL = window.URL.createObjectURL(blob);
        var link = document.createElement('a');
        link.href = downloadURL;
        link.download = attachment.fileName;
        link.click();
      },
      (response: HttpErrorResponse) => {
        if (response.status == 404){
          this.snackBar.open('Soubor nenalezen.', 'zavřít', { duration: 2000 });
        }
      }
    );
  }

}
