import {
  Component,
  OnDestroy,
  OnInit,
  ViewEncapsulation,
  ViewChild,
  ElementRef
} from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Location } from '@angular/common';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

import { fuseAnimations } from 'src/@fuse/animations';
import { FuseUtils } from 'src/@fuse/utils';

import universalParse from 'id3-parser/lib/universal';
import { IID3Tag } from 'id3-parser/lib/interface';

import { NgxFileDropEntry, FileSystemFileEntry } from 'ngx-file-drop';

@Component({
  selector: 'app-pages-medias-media-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.scss'],
  encapsulation: ViewEncapsulation.None,
  animations: fuseAnimations
})
export class DetailComponent implements OnInit, OnDestroy {
  media: any;
  pageType: string;
  mediaForm: FormGroup;
  id3Tag: IID3Tag | null;

  @ViewChild('testImage', { static: true })
  testImage: ElementRef;

  // Private
  private _unsubscribeAll: Subject<any>;

  /**
   * Constructor
   */
  constructor(
    private _formBuilder: FormBuilder,
    private _location: Location,
    private _matSnackBar: MatSnackBar
  ) {
    // Set the private defaults
    this._unsubscribeAll = new Subject();
  }

  // -----------------------------------------------------------------------------------------------------
  // @ Lifecycle hooks
  // -----------------------------------------------------------------------------------------------------

  /**
   * On init
   */
  ngOnInit(): void {
    // Subscribe to update product on changes
  }

  /**
   * On destroy
   */
  ngOnDestroy(): void {
    // Unsubscribe from all subscriptions
    this._unsubscribeAll.next();
    this._unsubscribeAll.complete();
  }

  // -----------------------------------------------------------------------------------------------------
  // @ Public methods
  // -----------------------------------------------------------------------------------------------------
  onMediaAdded(ev: any): void {
    universalParse(ev.target.files[0]).then(tags => {
      this.id3Tag = tags;
      const b64encoded =
        `data:${tags.image.mime};base64,` +
        btoa(String.fromCharCode.apply(null, tags.image.data));
      console.log(b64encoded);
      this.testImage.nativeElement.src = b64encoded;
    });
  }

  onFileDropped(files: NgxFileDropEntry[]) {
    console.log(files[0].fileEntry);

    const fileEntry = files[0].fileEntry as FileSystemFileEntry;

    fileEntry.file((file: File) => {
      universalParse(file).then(tags => {
        this.id3Tag = tags;
        const b64encoded =
          `data:${tags.image.mime};base64,` +
          btoa(String.fromCharCode.apply(null, tags.image.data));

        this.testImage.nativeElement.src = b64encoded;
      });
    });
  }
}
