import { Location } from '@angular/common';
import { Component, OnInit, ChangeDetectionStrategy, Inject, ChangeDetectorRef } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Router, ActivatedRoute } from '@angular/router';
import { throwError } from 'rxjs';
import { tap, catchError, filter } from 'rxjs/operators';
import { BaseForm } from 'src/app/core/base/base-form';
import { RecipientSignatureService } from 'src/app/core/service/settings/recipient-signature.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';
import { UploadService } from 'src/app/core/service/upload/upload.service';

@Component({
  selector: 'app-form-dialog',
  templateUrl: './form-dialog.component.html',
  styleUrls: ['./form-dialog.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class FormDialogComponent extends BaseForm implements OnInit {
  selectfile;
  constructor(
    public router: Router,
    public fb: FormBuilder,
    public activeRoute: ActivatedRoute,
    public location: Location,
    public dialogRef: MatDialogRef<FormDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data,
    private recipientSignatureSV: RecipientSignatureService,
    private swSV: SweetalertService,
    private uploadSV: UploadService,
    private cdr: ChangeDetectorRef
  ) {
    super(router,activeRoute,fb,location)
   }

  ngOnInit(): void {
    if(this.data){
      this.recipientSignatureSV.get(this.data).pipe(
        tap(x => this.form.patchValue(x)),
        tap(x => this.cdr.detectChanges())
      ).subscribe()
    }
  }

  createForm(): FormGroup {
    return this.fb.group({
      status_id: null,
      recipient_signature_uid: null,
      recipient_signature_code: null,
      recipient_signature_name_th: null,
      recipient_signature_name_en: null,
      recipient_signature_file_name: null,
      recipient_signature_url: null,
      is_default: null,
    })
  }

  onSelectFile(event) {
    if (event.target.files && event.target.files[0]) {
      this.selectfile = event.target.files[0];
      this.upload()
    }
  }

  upload(){
    const formData: FormData = new FormData();
    formData.append('file', this.selectfile, this.selectfile.name);
    this.uploadSV.uploadDocument(formData).pipe(
      filter((x:any) => x.status == 'success'),
      tap(x => this.form.get('recipient_signature_file_name').setValue(x.message[0].name)),
      tap(x => this.form.get('recipient_signature_url').setValue(x.message[0].file_name)),
      tap(x => this.cdr.detectChanges()),
      catchError(err => {
        this.swSV.errText(err.error)
        return throwError(err)
      })
    ).subscribe()
  }

  open(){
    if(this.form.get('recipient_signature_url').value){
      window.open(this.form.get('recipient_signature_url').value)
    }
  }

  save(){
    const form = this.form.getRawValue()
    if(this.data){
      this.recipientSignatureSV.update2(form).pipe(
        tap(x => this.swSV.updateSuccess()),
        tap(x => this.dialogRef.close()),
        catchError(err => {
          this.swSV.errText(err.error.description)
          return throwError(err)
        })
      ).subscribe()
      return
    }
    this.recipientSignatureSV.add(form).pipe(
      tap(x => this.swSV.saveSuccess()),
      tap(x => this.dialogRef.close()),
      catchError(err => {
        this.swSV.errText(err.error.description)
        return throwError(err)
      })
    ).subscribe()
  }


}
