import { LocationStrategy } from '@angular/common';
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { AuthenticationService } from '../../services/authenticate.service';
import { CredentialService } from '../../services/credential.service';
import { FormConstants } from '../../utils/enums';
import { ButtonManagementService } from '../../services/button-management.service';
import { StorageService } from '../services/storage.service';
import { LOGIN_ROUTE } from '../../utils/app.constants';


@Injectable(
    { providedIn: 'root' }
)
export class AuthenticationGuard implements CanActivate {

    constructor(private router: Router, private authService: AuthenticationService, private location: LocationStrategy, private credentialService: CredentialService,private buttonManagementService: ButtonManagementService, private storageService: StorageService) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

        if (state.url.includes('first-login-change-password')) {
            return true;
        }
        if (typeof window !== 'undefined' && window.localStorage) {
            const userStr = this.storageService.getItem('user');
            if (!userStr) {
                this.authService.logout();
                return false;
            }
            const data = JSON.parse(userStr);

            if ((data?.requiresPasswordChange || data?.user?.firstLogin) && 
                !state.url.includes('changePassword')) {
                this.router.navigate(['/first-login-change-password']);
                return false;
            }

            if (this.authService.isAuthenticated()) {  
                
                this.credentialService.setPorOrgacode(window.localStorage.getItem(FormConstants.POR_ORGACODE) || '');
                this.credentialService.setUserId(window.localStorage.getItem(FormConstants.USER_ID) || '');
                this.credentialService.setPassword(window.localStorage.getItem(FormConstants.PASSWORD) || '');
                this.credentialService.setToken(data.token);
                this.credentialService.setUserType(data.user.role);
                
                let permission = JSON.parse(window.localStorage.getItem('permission') || '[]');
                this.credentialService.setPermission(permission);
                this.buttonManagementService.setButtonPermissions(this.credentialService.getPermission(), this.authService.isAdminUser());   
                this.authService.onAuthenticationComplete.next(true);
                return true;
            }
             else {
                if(this.router.url != LOGIN_ROUTE){
                    this.authService.logout();
                }
                return false;
            }


        }
        return false;
    }

}