import { MatSnackBar } from '@angular/material/snack-bar';
import { Attachment } from './../model/Attachment.model';
import { FormControl, Validators, FormArray } from '@angular/forms';
import { FormGroup } from '@angular/forms';
import { New } from './../model/New.model';
import { Component, OnInit, Inject, Renderer2 } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { User } from 'src/app/core/model/user.model';
import * as moment from 'moment';
import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic';
import { NewAuthor } from '../model/NewAuthor.model';
import { RoleUtil } from 'src/app/core/role.util';
import { NewsService } from '../news.service';

export interface newEditDialogData{
  new: New;
  user: User;
}

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

  private user: User;
  private editMode = false;
  public newForm: FormGroup;

  private loadingFilesInProgress = false;

  public Editor = ClassicEditor;

  constructor(
    public dialogRef: MatDialogRef<NewsEditComponent>, 
    @Inject(MAT_DIALOG_DATA) public data: newEditDialogData, 
    public roleUtil: RoleUtil,
    private renderer: Renderer2,
    private newsService: NewsService,
    private snackBar: MatSnackBar
  ) {
    if (data.new)
      this.editMode = true;
    this.user = data.user;
    this.newForm = this.initNewForm(data.new);
  }

  ngOnInit() {
  }

  private initNewForm(item?: New){
    let attachments: FormControl[] = item ? item.attachments.map((attachment: Attachment) => new FormControl(attachment)) : [];
    let controls = {
      'id': new FormControl(item ? item.id : null),
      'title': new FormControl(item ? item.title : null, [Validators.required, Validators.maxLength(500)]),
      'text': new FormControl(item ? item.text : null, [Validators.required, Validators.maxLength(10000)]),
      'attachments': new FormArray(attachments),
      'author': new FormControl(item ? item.author : null),
      'created': new FormControl(item ? item.created : null)
    }
    return new FormGroup(controls);
  }

  private processedForm(){
    if (!this.editMode){
      this.newForm.get('author').setValue(new NewAuthor(this.user.id, <string>this.user.firstName, <string>this.user.lastName));
      this.newForm.get('created').setValue(moment());
    }
    return this.newForm;
  }

  private onAttachementsChanged(event: any){
    let fileList: FileList = event.target.files;
    let filesToLoad = fileList.length;
    if (filesToLoad > 5){
      this.snackBar.open('Nelze vložit víc jak 5 příloh najednou.', 'zavřít', { duration: 3000 });
      return;
    }

    let forbiddenFiles: string[] = [];
    for (let i = 0; i < fileList.length; i++){
      let reader = new FileReader();
      let file: File = fileList.item(i);
      if (file.size > (20 * 1024 * 1024)){
        forbiddenFiles.push(file.name);
        filesToLoad--
        this.loadingFilesInProgress = filesToLoad < 1 ? false : true;
        continue;
      }
      reader.readAsDataURL(file);
      reader.onload = () => {
        let currentAttachments: FormArray = this.newForm.get('attachments') as FormArray;
        let newAttachment: Attachment = new Attachment(file.name, file.type, (<string>reader.result).split(',')[1]);
        currentAttachments.push(new FormControl(newAttachment));
      };
      reader.onloadend = () => {
        filesToLoad--;
        this.loadingFilesInProgress = filesToLoad < 1 ? false : true;
      }
    }
    if (forbiddenFiles.length > 0){
      let snackBarText: string = (forbiddenFiles.length > 1 ? 'Přílohy ' : 'Přílohu ') + forbiddenFiles.join(", ") + ' nebylo možné přidat, jelikož ' + (forbiddenFiles.length > 1 ? 'jejich' : 'jeho') + ' velikost přesahuje 20 MB (20 971 520 B)';
      this.snackBar.open(snackBarText, 'zavřít');
    }
  }

  private onRemoveClick($event: any, attachmentToDelete: Attachment){
    let matListItem = $event.target.closest('mat-list-item');
    let attachments: FormArray = this.newForm.get('attachments') as FormArray;
    let index: number = attachments.value.findIndex((attachment: Attachment) => attachment === attachmentToDelete);
    if (index > -1 && matListItem !== null){
      this.renderer.addClass(matListItem, "hidden");
      setTimeout(() => attachments.removeAt(index), 200);
    }
  }

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