// Angular Core
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

// RxJs
import { Subscription, throwError } from 'rxjs';
import { catchError } from "rxjs/operators";

// Services
import { ExportFileService } from '../../services/exportFile/export-file.service';
import { PageAuthorizationService } from 'src/app/services/pageAuthorization/page-authorization.service';
import { AccountInfoService } from 'src/app/services/accountInfo/account-info.service';
import { SessionService } from 'src/app/services/session/session.service';
import { SessionDataInterface } from 'src/app/interfaces/session-data-interface';
import { DataTransmitterService } from 'src/app/services/dataTransmitter/data-transmitter.service';

@Component({
  standalone: false,
  selector: 'app-account-verify',
  templateUrl: './account-verify.component.html',
  styleUrls: ['./account-verify.component.scss']
})
export class AccountVerifyComponent implements OnInit, OnDestroy {

  accountVerifyForm: any = FormGroup;
  session!: SessionDataInterface['data'];
  regActiveStep!: string;
  isBuyer!: boolean;
  renderMe!: boolean;
  sitename!: string;
  sitenameListener!: Subscription;

  constructor(
    private formBuilder: FormBuilder,
    private accountInfoService: AccountInfoService,
    private pageAuthorizationService: PageAuthorizationService,
    private exportFileService: ExportFileService,
    private sessionService: SessionService,
    private router: Router,
    private dataTransmitter: DataTransmitterService
  ) { }

  ngOnInit(): void {
    this.session = this.sessionService.getSession();
    this.regActiveStep = this.session.is_supplier ? 'step3' : 'step6';
    this.isBuyer = this.session.is_buyer;
    this.renderMe = this.session.logged_in && (this.session.reg_step === 7);
    this.sitenameListener = this.dataTransmitter.sitename.subscribe((sitename) => {
      this.sitename = sitename;
    });

    this.accountVerifyForm = this.formBuilder.group({
      agreement_confirm: [false, Validators.required],
      signer_name: ['']
    });

  }

  get accountVerifyData() { return this.accountVerifyForm.controls; }

  saveUserInfoSubscribe!:Subscription;
  getUserAgreementDocSubscribe!:Subscription;
  saveAccountVerifyInfo() {
    let accVerifyInfo = {
      'agreed_to_terms': this.accountVerifyData.agreement_confirm.value,
      'xu_account_approve_signature': this.accountVerifyData.signer_name.value
    };
    this.saveUserInfoSubscribe = this.accountInfoService.saveUserInfo(accVerifyInfo)
      .pipe(
        catchError(() => {
          return throwError(() => new Error('ups sommething happend'));
        })
      ).subscribe({
        next: (res: any) => {
          this.sessionService.reCheckSession();
          let response = res;
          if (this.session.is_buyer) {
            this.router.navigate(['/market/home']);
          } 
          if(this.session.is_supplier) {
            this.router.navigate(['/market/supplier/home']);
          }
        },
        error: (err: HttpErrorResponse) => {
          this.accountInfoService.errorCallBack(err);
        },
        complete: () => { }
      });
  };

  validateAccountVerifyForm() {
    if (this.accountVerifyForm.invalid) {
      return true;
    } else {
      return false;
    }
  };

  /** Method introduced as part of TRX-8411
   * Method to download User Agreement Document
   * 
   * @returns void
  */
  downloadAgreement() {

    this.getUserAgreementDocSubscribe = this.accountInfoService.getUserAgreementDoc()
      .pipe(
        catchError(() => {
          return throwError(() => new Error('ups sommething happend'));
        })
      )
      .subscribe({
        next: (res: any) => {
          let response = res;
          if (response.data.contents) {
            var binary = atob(response.data.contents.replace(/\s/g, ''));
            var len = binary.length;
            var buffer = new ArrayBuffer(len);
            var fileData = new Uint8Array(buffer);
            for (var i = 0; i < len; i++) {
              fileData[i] = binary.charCodeAt(i);
            }
            this.exportFileService.exportFileByExtension('user_agreement', fileData, 'pdf', 'application/pdf');
          }
        },
        error: (err: HttpErrorResponse) => {
          this.accountInfoService.errorCallBack(err);
        },
        complete: () => { }
      });

  };

  ngOnDestroy(){
    this.saveUserInfoSubscribe?.unsubscribe();
    this.getUserAgreementDocSubscribe?.unsubscribe();
    this.sitenameListener.unsubscribe();
  }

}
