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

@Injectable()

export class AuthGuardService implements CanActivate {
	private UserSub: Subscription = new Subscription();
	private addr = '';
	private paid = false;
	private paidUpdate: Observable<boolean>;
	constructor(
		private router: Router,
		private http: HttpClient,
		public userService: UserService
	){
		this.paidUpdate = this.userService.paidUpdate;
		this.paidUpdate.subscribe((indicator) => {
			this.paid = indicator;
		});
	}

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

		if(token != null){
			this.userService.uZaddrUpdate.
				subscribe((addr) => {
				if (addr != null) {
					console.log(addr);
					this.addr = addr;
				} else {
					console.log("No record for that token");
				}
			});
			if (path === 'biz') {
				if (this.addr.length > 0) {
					return true;
				} else {
					this.router.navigate(['/login']);
					return false;
				}
			} else {
				if (this.addr != null && this.paid) {
					return true;
				} else {
					this.router.navigate(['/login']);
					return false;
				}
			}
		} else {
			console.log("Not logged in");
			this.router.navigate(['/login']);
			return false;
		}
	}
}
