import { Injectable } from '@angular/core';
import { Router, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import {HttpClient, HttpParams} from '@angular/common/http';
import { UserService } from './user.service';
import { Observable } from 'rxjs';


@Injectable()

export class AuthGuardService  {
	private addr = '';
	private paid = false;
	private paidUpdate: Observable<boolean>;
	constructor(
		private router: Router,
		public userService: UserService
	){
		this.userService.findUser();
		this.paidUpdate = this.userService.paidUpdate;
		this.paidUpdate.subscribe((indicator) => {
			this.paid = indicator;
		});
	}

	canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
		const token = localStorage.getItem('s4z_token');
		
		var path = route.url[0].path;

		if(token != null){
			if (path === 'biz') {
				this.userService.checkUser()?.subscribe( response => {
					if (response.status == 200 && response.body?.validated) {
						return true;
					} else {
						this.router.navigate(['/login']);
						return false;
					}
				});
			} else {
				this.userService.checkUser()?.subscribe( response => {
					if (response.status == 200 && response.body?.validated && this.paid) {
						return true;
					} else {
						this.router.navigate(['/login']);
						return false;
					}
				});
			}
		} else {
			console.log("Not logged in");
			this.router.navigate(['/login']);
			return false;
		}
	}
}
