import {
  AfterViewInit,
  Component,
  ElementRef,
  OnInit,
  ViewChild,
  ViewEncapsulation
} from '@angular/core'
import { SasService } from '../../services/sas.service'
import * as marked from 'marked'
import { EULA } from 'src/environments/_eula'
import { RequestWrapperResponse } from 'src/app/models/request-wrapper/RequestWrapperResponse'

@Component({
  selector: 'app-terms',
  templateUrl: './terms.component.html',
  styleUrls: ['./terms.component.scss'],
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class TermsComponent implements OnInit, AfterViewInit {
  @ViewChild('markdownCard') markdownCard!: ElementRef

  public agreeChecked: boolean = false
  public agreeBoxLocked: boolean = true
  public agreeClicked: boolean = false

  public eula_markdown = EULA

  constructor(private sasService: SasService) {}

  ngOnInit(): void {
    const md = marked.marked.setOptions({})
    this.eula_markdown = md.parse(this.eula_markdown)
  }

  ngAfterViewInit(): void {
    // We will fire SCROLL event that will recalculate and enable checkbox in case when
    // licence is short and no scroll is present
    setTimeout(() => {
      if (this.markdownCard)
        this.markdownCard.nativeElement.dispatchEvent(new CustomEvent('scroll'))
    })
  }

  termsAgreeChange() {
    if (!this.agreeChecked) {
      return
    }

    this.agreeBoxLocked = true
    this.agreeClicked = true

    let table = { SASControlTable: [{ ACCEPTED: 'yes' }] }

    this.sasService
      .request(`public/registeruser`, table)
      .then((res: RequestWrapperResponse) => {
        if (
          res.adapterResponse.return &&
          res.adapterResponse.return[0] &&
          res.adapterResponse.return[0].MSG === 'SUCCESS'
        ) {
          location.reload()
        }
      })
      .catch((err: any) => err)
      .finally(() => {
        //Timeout is added to improve UX
        //Without it, spinner would stop, and after one second app is reloaded
        //at that point it gives false impresion that accepting didn't work
        //with timeout spinner is visible all the time until page reloads
        setTimeout(() => {
          this.agreeBoxLocked = false
          this.agreeClicked = false
          this.agreeChecked = false
        }, 1000)
      })
  }

  onCardBlockScroll(event: any) {
    if (!this.agreeClicked) {
      let card_block_el: any = event.target

      if (card_block_el) {
        let pos = card_block_el.scrollTop + card_block_el.offsetHeight
        let max = card_block_el.scrollHeight - 20

        if (pos >= max) {
          this.agreeBoxLocked = false
        } else {
          this.agreeBoxLocked = true
        }
      }
    }
  }
}
