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

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

// Services
import { SessionService } from 'src/app/services/session/session.service';
import { AccountInfoService } from 'src/app/services/accountInfo/account-info.service';
import { ContentService } from 'src/app/services/content/content.service';
import { LocalStorageService } from 'src/app/services/localstorage/local-storage.service';

// Interfaces
import { SessionDataInterface } from 'src/app/interfaces/session-data-interface';
import { DocumentConfig } from 'src/app/interfaces/common-interfaces';
import { UtilitiesService } from 'src/app/services/utilities/utilities.service';
import { environment } from 'src/environments/environment';
import { DataTransmitterService } from 'src/app/services/dataTransmitter/data-transmitter.service';
import { DOCUMENT } from '@angular/common';

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

    session!: SessionDataInterface['data'];
    isBuyer!: boolean;
    renderMe!: boolean;
    regActiveStep!: string;
    isReadyToValidate: boolean = false;
    uploadedDocs: string[] = [];
    deaText: string = '';
    message: string = '';
    resaleApplicationDocument: string = '';
    statusType!: string;
    showErrMsg: boolean = false;
    imgUrl: string = environment.imageUrl;
    sitename!: string;
    sitenameListener!: Subscription;private readonly window = inject(DOCUMENT)?.defaultView as any;
    gtag: any = this.window?.gtag;

    /**
     * Upload-document directive related variables
     */
    stateLicenseDocConfig: DocumentConfig = {
        param: 'state_medical_license_document',
        buttonName: 'Upload State',
        className: 'col-xs-8 col-sm-8 col-md-8 col-lg-8',
        buttonClass: 'col-xs-4 col-sm-4 col-md-4 col-lg-4',
        statusMsgClass: 'col-xs-4 col-sm-4 col-md-4 col-lg-4 align-status-msg',
        error: false,
        errorMsg: '',
        accFileTypes: []
    };
    deaMedicalLicenseDocConfig: DocumentConfig = {
        param: 'dea_medical_license_document',
        buttonName: 'Upload DEA/HIN',
        className: 'col-xs-8 col-sm-8 col-md-8 col-lg-8',
        buttonClass: 'col-xs-4 col-sm-4 col-md-4 col-lg-4',
        statusMsgClass: 'col-xs-4 col-sm-4 col-md-4 col-lg-4 align-status-msg',
        error: false,
        errorMsg: '',
        accFileTypes: []
    };
    resaleAppDocConfig: DocumentConfig = {
        param: 'resale_application_document',
        buttonName: 'Upload Resale Cert',
        className: 'col-xs-8 col-sm-8 col-md-8 col-lg-8',
        buttonClass: 'col-xs-4 col-sm-4 col-md-4 col-lg-4',
        statusMsgClass: 'col-xs-4 col-sm-4 col-md-4 col-lg-4 align-status-msg',
        errorMsg: '',
        accFileTypes: [],
        error: false
    };
    durReportDocConfig: DocumentConfig = {
        param: 'dur_report_document',
        buttonName: 'Upload DUR',
        className: 'col-xs-8 col-sm-8 col-md-8 col-lg-8',
        buttonClass: 'col-xs-4 col-sm-4 col-md-4 col-lg-4',
        statusMsgClass: 'col-xs-4 col-sm-4 col-md-4 col-lg-4',
        errorMsg: '',
        accFileTypes: ['jpg', 'jpeg', 'rtf', 'png', 'pdf', 'pict', 'tiff', 'xls', 'xlsx', 'csv', 'txt', 'doc', 'docx'],
        error: false
    };
    glnDocConfig: DocumentConfig = {
        param: 'gln_document',
        buttonName: 'Upload GLN',
        className: 'col-xs-8 col-sm-8 col-md-8 col-lg-8',
        buttonClass: 'col-xs-4 col-sm-4 col-md-4 col-lg-4',
        statusMsgClass: 'col-xs-4 col-sm-4 col-md-4 col-lg-4 align-status-msg',
        errorMsg: '',
        accFileTypes: [],
        error: false
    };

    /**
     * End of upload-document directive variables
     */
    constructor(
        private router: Router,
        private accountInfoService: AccountInfoService,
        private sessionService: SessionService,
        private contentService: ContentService,
        private localStorageService: LocalStorageService,
        private utilities: UtilitiesService,
        private dataTransmitter: DataTransmitterService
    ) { }

    ngOnInit(): void {
        this.session = this.sessionService.getSession();
        this.isBuyer = this.session.is_buyer;
        this.renderMe = this.session.logged_in && (this.session.reg_step >= 6);
        this.regActiveStep = this.session.is_supplier ? 'step2' : 'step5';
        this.sitenameListener = this.dataTransmitter.sitename.subscribe((sitename) => {
            this.sitename = sitename;
        });
        this.getUserSession();
        this.getDocFlag();
    }

    /**
    * Get user session and return defer promise
    * @returns {.$q@call;defer.promise}
    */
    checkSession() {
        return new Promise((resolve) => {
            var r = this.sessionService.get();
            r.then(() => {
                this.session = this.sessionService.getSession();
                resolve(this.session);
            }).catch(err => {
                this.sessionService.errorCallBack(err);
            });
        })
    };

    getGoogleAnalyticsCodeSubscribe!:Subscription;
    getDocumentFlagsSubscribe!:Subscription;
    /**
     * Add google analytics code for production
     * @returns {undefined}
     */
    googleAnalytics() {
        this.getGoogleAnalyticsCodeSubscribe = this.contentService.getGoogleAnalyticsCode()
            .pipe(
                catchError(() => {
                    return throwError(() => new Error('ups sommething happend'));
                })
            )
            .subscribe({
                next: (res: any) => {
                    if (res.data.registration_ga_code) {
                        this.gtag('create', res.data.registration_ga_code, 'auto', {'name':'registrationTracker' });
                        this.gtag('set', 'page', '/market/licenseVerification');
                        this.gtag('registrationTracker.send', 'pageview');
                    }
                },
                error: (err: HttpErrorResponse) => {
                },
                complete: () => { }
            });
    };

    /**
     * Check session and redirect the user if true
     * @returns {undefined}
     */
    getUserSession() {
        this.checkSession().then(() => {
            if (this.session.logged_in) {
                if (this.session.account_status === "final") {
                    this.router.navigate(['/market/home'])
                }
                if (this.session.account_status === "valid") {
                    this.router.navigate(['/market/accountVerify'])
                }
                if (this.session.account_status === 'new') {
                    this.router.navigate(['/market/storeInfo'])
                }
            } else {
                this.localStorageService.clear();
                this.router.navigate(['/market/login'])
            }
            this.googleAnalytics();
            this.trackGoogleAdConversion();
            this.deaText = 'DEA';
            if (this.session.is_hin === true) {
                this.deaText = 'HIN';
            }
        }).catch(err => {
            /**if your asynchronous function returns defer.reject()
             instead of defer.resolve() you can catch the error here**/
        })
    };

    /**
     * Sets readyToValidate flag to true
     * when button is clicked on UI
     * @returns {undefined}
     */
    readyToValidate() {
        this.isReadyToValidate = true;
    };

    /**
     * Enable Ready to Validate button basing on
     * type of documents and number of documents
     * uploaded.
     * 
     * @returns {boolean}
     */
    disableReadyToValidate() {
        var disable = true;
         if (this.uploadedDocs.length >= 2
            && this.uploadedDocs.includes('dea_medical_license_document')
            && this.uploadedDocs.includes('state_medical_license_document')) {
            disable = false;
        }

        return disable;
    };

     /**
     * Initialize license verification controller
     * and fetch required data needed for the controller to load
     * @returns {undefined}
     */
      getDocFlag() {
        this.getDocumentFlagsSubscribe = this.accountInfoService.getDocumentFlags()
        .pipe(
            catchError(() => {
                return throwError(() => new Error('ups sommething happend'));
            })
        )
        .subscribe({
            next: (res: any) => {
                res.data;
                if (res.data.dea_medical_license_document 
                    && res.data.state_medical_license_document) {
                    this.readyToValidate();
                }
                Object.entries(res.data).forEach(([key, value]) => {
                    if (value) {
                        this.uploadedDocs.push(key);
                    }
                });
            },
            error: (err: HttpErrorResponse) => {
                this.accountInfoService.errorCallBack;
            },
            complete: () => { }
        });
    };

  /**
   * Build configuration object for document upload component.
   * @param documentType 
   * @param accFileTypes 
   * @returns DocumentConfig
   */
  getDocumentConfig(documentType: string, accFileTypes = []): DocumentConfig
  {
      let config: DocumentConfig =  {
        param: documentType,
        className: 'padding-top-1',
        buttonName: 'Upload New',
        error: false,
        errorMsg: '',
        accFileTypes: []
      };
      if (accFileTypes.length !== 0) {
          config.accFileTypes = accFileTypes;
      }
      return config;
  }

  /**
   * Check if a document is already uploaded.
   * @param docName 
   * @returns boolean
   */
  isDocUploaded(docName: string) {
    return Number((this.uploadedDocs.indexOf(docName) > -1));
  }

  /**
   * Update document config with the object sent by upload document directive
   * after the upload document process is complete.
   * @param docConfig 
   */
  updateDocConfig(docConfig: DocumentConfig) {
    switch (docConfig.param) {
      case 'state_medical_license_document':
        this.utilities.merge(this.stateLicenseDocConfig, docConfig);
        break;
      case 'dea_medical_license_document':
        this.utilities.merge(this.deaMedicalLicenseDocConfig, docConfig);
        break;
      case 'resale_application_document':
        this.utilities.merge(this.resaleAppDocConfig, docConfig);
        break;
      case 'gln_document':
        this.utilities.merge(this.glnDocConfig, docConfig);
        break;
    }

    if (docConfig.uploadStatus) {
        if (!this.uploadedDocs.includes(docConfig.param)) {
            this.uploadedDocs.push(docConfig.param);
        }
        if (this.uploadedDocs.length >= 4) {
            this.readyToValidate();
        }
    }
  }

    ngOnDestroy(){
        this.getGoogleAnalyticsCodeSubscribe?.unsubscribe();
        this.getDocumentFlagsSubscribe?.unsubscribe();
        this.sitenameListener.unsubscribe();
    }

    /**
     * Event snippet for OM-ConfirmEmail conversion page
     */
    trackGoogleAdConversion() {
        this.gtag('event', 'conversion', {
            'send_to': 'AW-1012179571/Jb2MCIqA-s0ZEPPE0uID',
            'value': 1.0,
            'currency': 'USD'
        });
    }
}
