import { Component, OnInit, ViewEncapsulation } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { AppService, LicenceService, SasService } from '../services'
import { LicenseKeyData } from '../models/LicenseKeyData'
import { RequestWrapperResponse } from '../models/request-wrapper/RequestWrapperResponse'

enum LicenseActions {
  key = 'key',
  register = 'register',
  limit = 'limit',
  update = 'update'
}

@Component({
  selector: 'app-licensing',
  templateUrl: './licensing.component.html',
  styleUrls: ['./licensing.component.scss'],
  encapsulation: ViewEncapsulation.None,
  standalone: false
})
export class LicensingComponent implements OnInit {
  public action: LicenseActions | null = null

  public licenseErrors: { [key: string]: string } = {
    missing: `Licence key is missing - please contact <a class="color-green" href="mailto: support@datacontroller.io">support@datacontroller.io</a> and enter valid keys below.`,
    expired: `Licence key is expired - please contact <a class="color-green" href="mailto: support@datacontroller.io">support@datacontroller.io</a> and enter valid keys below.`,
    invalid: `Licence key is invalid - please contact <a class="color-green" href="mailto: support@datacontroller.io">support@datacontroller.io</a> and enter valid keys below.`,
    missmatch: `Your SYSSITE (below) is not found in the licence key - please contact <a class="color-green" href="mailto: support@datacontroller.io">support@datacontroller.io</a> and enter valid keys below.`
  }

  public keyError: string | undefined
  public errorDetails: string | undefined
  public missmatchedKey: string | undefined
  public licenceKeyValue: string = ''
  public activationKeyValue: string = ''

  public applyingKeys: boolean = false
  public protocol: string =
    location.protocol === 'https:'
      ? 'HTTPS - secure connection'
      : 'HTTP - insecure connection'

  public syssite = this.appService.syssite
  public currentLicenceKey = this.licenceService.licenceKey
  public currentActivationKey = this.licenceService.activationKey
  public isAppFreeTier = this.licenceService.isAppFreeTier
  public userCountLimitation = this.licenceService.userCountLimitation

  public licenseKeyData: LicenseKeyData | null = null

  public inputType: 'file' | 'paste' = 'file'
  public licenceFileError: string | undefined
  public licenceFileLoading: boolean = false
  public licencefile: { filename: string } = {
    filename: ''
  }

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private licenceService: LicenceService,
    private sasService: SasService,
    private appService: AppService
  ) {}

  ngOnInit(): void {
    this.licenceKeyValue = this.currentLicenceKey || ''
    this.activationKeyValue = this.currentActivationKey || ''

    this.route.queryParams.subscribe((queryParams: any) => {
      this.keyError = queryParams.error
      this.missmatchedKey = queryParams.missmatchId

      if (queryParams.details) {
        this.errorDetails = atob(queryParams.details)
      }
    })

    this.route.params.subscribe((params: any) => {
      let actionInUrl = params.action

      if (actionInUrl) {
        if (Object.values(LicenseActions).includes(actionInUrl)) {
          this.action = actionInUrl
        }
      }
    })

    this.licenseKeyData = this.licenceService.getLicenseKeyData()
  }

  public trimKeys() {
    this.licenceKeyValue = this.licenceKeyValue.trim()
    this.activationKeyValue = this.activationKeyValue.trim()
  }

  public copySyssite(copyIconRef: any, copyTooltip: any, syssite: string[]) {
    const syssiteString = syssite.join('\n')

    navigator.clipboard.writeText(syssiteString).then(() => {
      copyIconRef.setAttribute('shape', 'check')
      copyIconRef.setAttribute('class', 'is-success')
      copyTooltip.innerText = 'Copied!'

      setTimeout(() => {
        copyIconRef.setAttribute('shape', 'copy')
        copyIconRef.removeAttribute('class')
        copyTooltip.innerText = 'Copy to clipboard'
      }, 1000)
    })
  }

  public applyKeys() {
    this.applyingKeys = true

    let table = {
      keyupload: [
        {
          ACTIVATION_KEY: this.activationKeyValue,
          LICENCE_KEY: this.licenceKeyValue
        }
      ]
    }

    this.sasService
      .request('admin/registerkey', table)
      .then((res: RequestWrapperResponse) => {
        if (
          res.adapterResponse.return &&
          res.adapterResponse.return[0] &&
          res.adapterResponse.return[0].MSG === 'SUCCESS'
        ) {
          this.router.navigateByUrl('/').then(() => {
            window.location.reload()
          })
        }
      })
      .finally(() => {
        this.applyingKeys = false
      })
  }

  public onFileCapture(event: any, dropped = false) {
    let file = dropped ? event[0] : event.target.files[0]
    this.licencefile.filename = file.name

    if (!file) return

    this.licenceFileLoading = true

    const reader = new FileReader()

    reader.onload = (evt) => {
      this.licenceFileError = 'Error reading file.'

      if (!evt || !evt.target) return
      if (evt.target.readyState != 2) return
      if (evt.target.error) return
      if (!evt.target.result) return

      this.licenceFileLoading = false
      this.licenceFileError = undefined
      const fileArr = evt.target.result.toString().split('\n')
      this.activationKeyValue = fileArr[1]
      this.licenceKeyValue = fileArr[0]
    }

    reader.readAsText(file)
  }

  public switchType(type: 'paste' | 'file') {
    this.inputType = type
  }

  get disableApplyButton(): boolean {
    if (this.licenceKeyValue.length < 1 || this.activationKeyValue.length < 1)
      return true
    if (
      this.licenceKeyValue === this.currentLicenceKey &&
      this.activationKeyValue === this.currentActivationKey
    )
      return true

    return false
  }
}
