import {AfterViewChecked, AfterViewInit, Component, ElementRef, Input, OnInit, ViewChild, ViewEncapsulation} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {UploadAttachService} from '../service/upload.attach.service';
import {UploadAnalysisModel} from '../models/upload.analysis.model';
import {UploadMetaModel} from '../models/uploadMetaModel';
import {FloatingActionButtonComponent} from '@progress/kendo-angular-buttons';
import {DrawerSelectEvent, TabStripComponent} from '@progress/kendo-angular-layout';
import {AnalysisAaaModel} from '../models/analysis.aaa.model';



@Component({
  selector: 'app-upload-detail',
  templateUrl: './upload-detail.component.html',
  styleUrls: ['./upload-detail.component.scss']
})
export class UploadDetailComponent implements OnInit, AfterViewInit {
  @Input() uploadId: number;
  @Input() ua: UploadAnalysisModel = new UploadAnalysisModel({});
  @ViewChild('fab', {static: true}) fab: FloatingActionButtonComponent;
  @ViewChild('pdf', {static: false}) pdf: ElementRef;
  @ViewChild('tabs', {static: true}) tab: TabStripComponent;
  // 'http://africau.edu/images/default/sample.pdf';
  public uploadAsPicUrl =  'https://svr2021.lawipac.com:8080/api/v1/upload-as-pdf/default';
  public uploadAsPdfUrl = '';
  public initAnimation = false;
  public iframeLoaded = false;
  public scanning = false;
  public scanDone = false;
  public analysisIsDone = false;

  public ScanImgLoaded = false;
  public PreviewImgLoaded = false;

  public resizeSplitter = false;
  public PayInSize = '300px';
  public fabOffset = { x: '10px', y: this.PayInSize };

  public currentTab = 0;
  public tabText: string[] = ['Preview', 'Content', 'Analysis'];
  public tabTitle: string[] = this.tabText;

  public analysisAAA: AnalysisAaaModel[] = [];

  constructor(private us: UploadAttachService, private actRoute: ActivatedRoute, private router: Router) { }

  ngOnInit(): void {
    const id  = this.actRoute.snapshot.params.id;
    if ( id !== undefined && id > 0 ) {
      this.uploadId = id;
    }

    this.ua.Id = this.uploadId;
    if ( this.uploadId > 0 ) {
      this.uploadAsPicUrl = this.us.getUploadAsJpgUrl(this.ua.Id);
      this.uploadAsPdfUrl = this.us.getUploadAsPdfUrl(this.ua.Id);
    }

    this.loadUploadMeta();
    this.fabSlideIn();
  }

  ngAfterViewInit(): void {
    setTimeout(() => { // if I don't use this, it complains value has been changed after being checked.
      this.tab.selectTab(this.currentTab);
    }, 100);
  }

  private loadUploadAnalysis(): void  {
    this.analysisIsDone = false;
    this.us.getUploadAnalysis(this.uploadId).subscribe(
      resp => {
       this.ua = new UploadAnalysisModel(resp);
       // this.TranslateForDisplay()  // TODO: use database for this structure
       this.uploadId = this.ua.Id;
       this.analysisIsDone = true;
      }, err => {
        this.analysisIsDone = true;
      }, () => {
        this.analysisIsDone = true;
      }
    );
  }
  private loadUploadMeta(): void {
    this.us.getUploadMeta(this.uploadId).subscribe(
      resp => {
        this.ua.Input = new UploadMetaModel(resp);
      }
    );
  }

  private startScanningUI(): void {
    this.resizeSplitter = false;
    this.scanning = true;
    let count = 0;
    const t = setInterval(() => {
      count ++;
      if (count > 30 && this.analysisIsDone) {  // 30 should be in sync with scss 3s
        this.scanDone = true;
        this.scanning = false;
        this.resizeSplitter = true;
        clearInterval(t);
      }
    }, 100);
  }

  private fabSlideIn(): void {
    setTimeout(() => {this.initAnimation = true; }, 1000);
  }

  public onClickFloatActionButton(e: any): void{
    this.router.navigate(['/lender-uploads']);
  }

  public finishedLoading(status: string ): void{
    if (this.pdf === undefined) {
      return;
    }
    const el = this.pdf.nativeElement;
    if (el !== undefined && el.src === this.uploadAsPdfUrl) {
      console.log('yes true', this);
      this.iframeLoaded = true;
    }
  }
  public onTabSelect( select: DrawerSelectEvent): void {
    this.currentTab = select.index;
    this.changeTabTitle();
    if ( select.index === 2 &&  ! this.scanDone ) {
      this.loadUploadAnalysis();
    }
  }

  private changeTabTitle(): void {
    this.tabTitle = [];
    for ( let i = 0; i < this.tabText.length; i++ ) {
      if ( i === this.currentTab ){
        this.tabTitle[i] = '☒ ' + this.tabText[i];
      }else{
        this.tabTitle[i] = '☐ ' + this.tabText[i];
      }
    }
  }

  public onImgPreviewLoaded(): void {
    this.PreviewImgLoaded = true;
  }

  public onImgScanLoaded(): void {
    this.ScanImgLoaded = true;
    this.startScanningUI();
  }



  public onPayInCollapsed( closed: boolean): void {
    console.log(this);
    this.resizeSplitter = !closed;
    return ;
  }

  public onPayInSizeChange(s: string): void {
    this.resizeSplitter = true;
    this.fabOffset = {x: '10px', y: s};
  }
}
