import { Attachment } from './../model/Attachment.model';
import { FormGroup } from '@angular/forms';
import { MatDialogRef, MatDialog } from '@angular/material/dialog';
import { LayoutService } from './../../core/layout.service';
import { User } from './../../core/model/user.model';
import { AuthState } from 'src/app/auth/store/auth.reducers';
import { Store } from '@ngrx/store';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { NewsFeatureState, NewsState } from '../store/news.reducers';
import { Subscription } from 'rxjs';
import { NewsService } from '../news.service';
import { New } from '../model/New.model';
import { RoleUtil } from 'src/app/core/role.util';
import { NewsEditComponent } from '../news-edit/news-edit.component';
import { DialogService } from 'src/app/core/dialog.service';

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

  private authStoreSubscription: Subscription;
  private storeSubscription: Subscription;

  public user: User;
  public news: New[] = [];
  private allFetched: boolean = false;

  private isReachingBottomSubscription: Subscription;
  private isReachingBottom: boolean;

  private hasScrollSubscription: Subscription;
  private hasScroll: boolean;

  private editDialogRef: MatDialogRef<NewsEditComponent>;

  constructor(
    private store: Store<NewsFeatureState>, 
    private newsService: NewsService, 
    public roleUtil: RoleUtil,
    private layoutService: LayoutService,
    private dialog: MatDialog,
    private dialogService: DialogService
  ) {
    this.authStoreSubscription = this.store.select('authState').subscribe(
      (state: AuthState) => {
        if (state.user)
          this.user = state.user;
      }
    );
    this.hasScrollSubscription = this.layoutService.hasScroll.subscribe(
      (hasScroll: boolean) => { this.hasScroll = hasScroll; }
    );
    this.storeSubscription = this.store.select('news').subscribe(
      (state: NewsState) => {
        if (state.news === null){
          this.layoutService.updateHasScroll.next();
          this.newsService.getNewsBatch();
        }
        else {
          this.news = state.news;
          if (state.news.length !== this.news.length){
            setTimeout(() => {
              this.layoutService.updateHasScroll.next();
              if(!this.hasScroll)
                this.layoutService.isReachingBottom.next(true);
            }, 0);
          }
          else{
            this.allFetched = true;
          }
        }
      }
    );
    this.isReachingBottomSubscription = this.layoutService.isReachingBottom.subscribe(
      (isReachingBottom: boolean) => {
        this.isReachingBottom = isReachingBottom;
        if (isReachingBottom !== false && !this.allFetched){
          let lastNew = this.news[this.news.length - 1];
          this.newsService.getNewsBatch(lastNew.id);
        }
      }
    )
  }

  ngOnInit() {
  }

  ngOnDestroy() {
    this.authStoreSubscription.unsubscribe();
    this.storeSubscription.unsubscribe();
  }

  private initEditDialog(item?: New){
    const dialogRef = this.dialog.open(NewsEditComponent, {
      width: '90%',
      maxWidth: '750px',
      height: '90%',
      maxHeight: '680px',
      data: { new: item, user: this.user }
    });

    dialogRef.afterClosed().subscribe(
      (newForm: FormGroup) => {
        if (newForm)
          this.newsService.saveNew(newForm.value);
      }
    );
  }

  private onDeleteNewClick(item: New){
    this.dialogService.confirm('Smazat novinku?', 'Opravdu si přejete smazat novinku "'+item.title+'" ?').subscribe(
      (result: any) => {
        if (result){
          this.newsService.deleteNew(item.id);
        }
      }
    );
  }

  private loadFile(attachment: Attachment){
    this.newsService.getAttachment(attachment);
  }

}
