import { Component, OnInit, ViewChild } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { trigger,state, style } from '@angular/animations';

import { ImageService } from '../../services/image.service';
import { ServiceComm } from '../../services/service-comm.service';
import { ImageResp } from '../../models/Image';
import { AddAction } from '../../models/add-action.enum';

@Component({
  selector: 'app-list-of-images',
  templateUrl: './list-of-images.component.html',
  styleUrls: ['./list-of-images.component.css'],
  animations: [
      trigger('rotatedState', [
        state('default', style({ transform: 'rotate(0)' })),
        state('rot90', style({ transform: 'rotate(-90deg)' })),
        state('rot180', style({ transform: 'rotate(-180deg)' })),
        state('rot270', style({ transform: 'rotate(-270deg)' })),
    ])
  ]
})
export class ListOfImagesComponent implements OnInit {
  public displayedColumns: Array<string> = ['comment', 'data'];
  public imgForm: FormGroup;
  public imageError: string;
  private selectedFile: string;
  public popinImage: string;
  public showPopin: boolean;
  public dataSourceTable: MatTableDataSource<ImageResp>;
  public resultsLength = 0;
  public stateRotation: string = 'default';
  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;

  constructor(
    private serviceApi: ImageService,
    private serviceComm: ServiceComm
  ) { }

  ngOnInit(): void {
    this.serviceComm.refreshRequest.subscribe((action) => {
      if (action === AddAction.Gear) {
        this.getListOfImages();
      }
    });
    this.getListOfImages();

    this.imgForm = new FormGroup({
      comment: new FormControl('', Validators.required),
      image: new FormControl('', Validators.required),
    });
  }

  private getListOfImages() {
    this.serviceApi.getListOfImages()
                   .subscribe((data) => {
                      setTimeout(() => {
                        this.dataSourceTable = new MatTableDataSource<ImageResp>(data);
                        this.dataSourceTable.paginator = this.paginator;
                        this.resultsLength = data.length;
                      }, 500);
                    });
  }

  public onFileChanged(fileInput: any) {
    const file = fileInput.dataTransfer
      ? fileInput.dataTransfer.files[0]
      : fileInput.target.files[0];
    const allowed_types = ['image/png', 'image/jpeg'];
    const max_size = 20971520;

    if (!allowed_types.includes(file.type)) {
      this.imageError = 'Only Images are allowed ( JPG | PNG )';
    } else if (file.size > max_size) {
      this.imageError = 'Maximum size allowed is ' + max_size / 1000 + 'Mb';
    } else {
      const reader = new FileReader();
      reader.onload = this.checkAndExtractDataToBase64.bind(this);
      reader.readAsDataURL(fileInput.target.files[0]);
    }
  }

  private checkAndExtractDataToBase64(e: any) {
    const max_height = 15200;
    const max_width = 25600;

    const image = new Image();
    image.src = e.target.result;
    image.onload = (rs) => {
      const img_height = rs.currentTarget['height'];
      const img_width = rs.currentTarget['width'];

      if (img_height > max_height && img_width > max_width) {
        this.imageError =
          'Maximum dimentions allowed ' + max_height + '*' + max_width + 'px';
      } else {
        const imgBase64Path = e.target.result;
        this.selectedFile = imgBase64Path;
        this.imageError = 'OK';
      }
    };
  }

  onSubmit(formData) {
    if (formData.invalid) {
      return;
    }

    this.serviceApi.AddImage(formData.comment, this.selectedFile)
                   .subscribe(
                     () => { this.getListOfImages(); }
                   );
  }

  openModal(image: ImageResp){
    this.popinImage = image.data;
    this.showPopin = true;
  }

  closeModal() {
    this.showPopin = false;
  }

  rotate() {
    if (this.stateRotation === 'default') {
      this.stateRotation = 'rot90';
    } else if (this.stateRotation === 'rot90') {
      this.stateRotation = 'rot180';
    } else if (this.stateRotation === 'rot180') {
      this.stateRotation = 'rot270';
    } else {
      this.stateRotation = 'default';
    }
  }
}
