import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { DetailsBase } from '@objects-view/details-base';
import { IUserModel } from '@fleio-api/client-user/model/user.model';
import { UserListUIService } from '../user-list-ui.service';
import { UsersApiService } from '@fleio-api/client-user/user/users-api.service';
import { AppLocalStorageService } from '@shared/ui-api/app-local-storage.service';
import { ConfigService } from '@shared/config/config.service';
import { TokenStorageService } from '@shared/ui-api/token-storage.service';

@Component({
  selector: 'app-user-impersonate',
  templateUrl: './user-impersonate.component.html',
  styleUrls: ['./user-impersonate.component.scss']
})
export class UserImpersonateComponent extends DetailsBase<IUserModel> implements OnInit {
  constructor(
    route: ActivatedRoute,
    userListUIService: UserListUIService,
    private usersApi: UsersApiService,
    private appLocalStorage: AppLocalStorageService,
    private config: ConfigService,
    private tokenStorage: TokenStorageService,
    private activatedRoute: ActivatedRoute,
  ) {
    super(route, userListUIService, 'edit', 'user');
  }

  ngOnInit() {
    super.ngOnInit();
    const clientId = this.activatedRoute.snapshot.paramMap.get('clientId');

    if (this.object) {
      this.usersApi.impersonate(this.object.id).subscribe((impersonationData: {
        fleio_token: {
          token: string;
          expire_at: string;
          expire_at_browser_close: boolean;
        };
      }) => {
        let currentPath = window.location.href;
        if (clientId) {
          // url contains client ID, need to cut it
          currentPath = currentPath.substring(0, currentPath.lastIndexOf('/'));
        }
        currentPath = currentPath.substring(0, currentPath.lastIndexOf('/') + 1);

        this.appLocalStorage.setItem('fleio.flStaffBackend', this.config.getPanelApiUrl(''), false);
        this.appLocalStorage.setItem('fleio.flStaffUrl', currentPath, false);
        this.tokenStorage.setPanelToken(
          'enduser',
          impersonationData.fleio_token.token,
          impersonationData.fleio_token.expire_at,
          impersonationData.fleio_token.expire_at_browser_close,
        );
        if (!clientId) {
          window.location.href = this.config.current.urls.enduserUrl;
        } else {
          window.location.href = this.config.current.urls.enduserUrl + `${clientId}`;
        }
      });
    }
  }
}
