// Angular Core
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router, ActivatedRoute } 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 { ConfirmEmailService } from '../../services/confirmEmail/confirm-email.service';
import { LocalStorageService } from 'src/app/services/localstorage/local-storage.service';
import { environment } from 'src/environments/environment';
import { SessionDataInterface } from 'src/app/interfaces/session-data-interface';
@Component({
  standalone: false,
  selector: 'app-confirm-email',
  templateUrl: './confirm-email.component.html',
  styleUrls: ['./confirm-email.component.scss']
})
export class ConfirmEmailComponent implements OnInit, OnDestroy {

  emailConfirmed: boolean = false;
  loginInfo: any = {};
  /*
  * Store passed url params
  * @type Object
  */
  urlParams = {
    confirm_key: '',
  };
  errorMessage: string = '';
  successMessage: string = '';
  expire: boolean = false;
  session!: SessionDataInterface['data'];
  isBuyer!: boolean;
  renderMe!: boolean;
  confirm_key:string = '';
  imgUrl: string = environment.imageUrl;

  constructor(
    private sessionService: SessionService,
    private confirmEmailService: ConfirmEmailService,
    private router: Router,
    private activateRoute: ActivatedRoute,
    private localStorageService: LocalStorageService
  ) { }

  ngOnInit(): void {
    this.session = this.sessionService.getSession();
    this.isBuyer = this.session.is_buyer;
    this.renderMe = this.session.logged_in && (this.session.is_email_confirmed === 0);
    this.checkConfirmKey();
    this.getUserSession();
  }
  
  confirmUserEmailSubscribe!:Subscription;
  resendConfirmEmailSubscribe!:Subscription;
  checkConfirmKey() {
    if (this.activateRoute.snapshot.queryParams['confirmKey']) {
      this.urlParams.confirm_key = this.activateRoute.snapshot.queryParams['confirmKey'];
      this.errorMessage = 'Confirm Key cannot be empty.';
      this.confirmUserEmailSubscribe = this.confirmEmailService.confirmUserEmail(this.urlParams)
        .pipe(
          catchError((err) => {
            return throwError(() => err);
          })
        )
        .subscribe({
          next: () => {
            this.emailConfirmed = true;
          },
          error: (err: HttpErrorResponse) => {
            if (err.error.feedback) {
              err.error.feedback.forEach((errorMessage: string) => {
                this.errorMessage = errorMessage;
              });
            }
          },
          complete: () => { }
        });
    }

  }

  confirmEmail() {
    this.resetMessages();
    this.confirmUserEmailSubscribe = this.confirmEmailService.confirmUserEmail({'confirm_key' : this.confirm_key})
      .pipe(
        catchError((err) => {
          return throwError(() => err);
        })
      )
      .subscribe({
        next: () => {
          this.emailConfirmed = true;
        },
        error: (err: HttpErrorResponse) => {
          if(err.error.feedback){
            err.error.feedback.forEach((errorMessage: string) => {
              this.errorMessage = errorMessage;
            });
          }else{
            this.errorMessage = "Confirmation key mismatch, please try again."
          }
        },
        complete: () => { }
      });
  };

  resendConfirmEmail() {
    this.expire = true;
    this.resetMessages();

    this.resendConfirmEmailSubscribe = this.confirmEmailService
      .resendConfirmEmail()
      .pipe(
        catchError((err) => {
          return throwError(() => err);
        })
      )
      .subscribe({
        next: (res: any) => {
          if (res.data === "1") {
            this.successMessage = "New Confirmation Key Sent to Email";
          } else {
            this.errorMessage = "There was an error sending the email.";
          }
        },
        error: (err: HttpErrorResponse) => {
          if (err.error.feedback) {
            err.error.feedback.forEach((errorMessage: string) => {
              this.errorMessage = errorMessage;
            });
          }
        },
        complete: () => { }
      });

  };

  /**
   * Reset errorMessage and successMessage to default values.
   * @returns {undefined}
  */

  resetMessages() {
    this.errorMessage = '';
    this.successMessage = '';
  };

  /**
   * 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);
      });
    })
  };

  /**
   * Check session and redirect the user if true
   * @returns {undefined}
   */
  getUserSession() {
    this.session = this.sessionService.getSession();
    if (this.session.logged_in) {
      this.loginInfo.username = this.session.username;
      this.loginInfo.email = this.session.email;
      this.loginInfo.reg_step = this.session.reg_step;
      this.loginInfo.message = this.session.message;
      if (this.loginInfo.reg_step === 2 && this.loginInfo.message !== 'Confirm Email Pending') {
        this.router.navigate(['/market/storeInfo'])
      }
    } else {
      this.localStorageService.clear();
      this.router.navigate(['/market/login'])
    }
  };

  emailConfirmationNext() {
    this.sessionService.reCheckSession();
    this.router.navigate(['/market/storeInfo'])
  };

  ngOnDestroy(){
    this.confirmUserEmailSubscribe?.unsubscribe();
    this.resendConfirmEmailSubscribe?.unsubscribe();
  }

}
