import { Injectable } from "@angular/core";
import {
  ActivatedRouteSnapshot,
  CanActivate,
  Router,
  RouterStateSnapshot,
  UrlTree,
} from "@angular/router";
import { from, Observable, of } from "rxjs";
import { AccountService } from "../server-services/account.service";
import { DialogService } from "src/app/shared/services/dialog.service";
import { RouterHandler } from "../services/router-handler.service";
import { marker } from "@biesbjerg/ngx-translate-extract-marker";
import { ServerRestApiService } from "../services/server-rest-api.service";
import { AuthService } from "../server-services/auth.service";
import { MatDialog } from "@angular/material/dialog";
import { ContactDialogComponent } from "../dialogs/contact-dialog/contact-dialog.component";
import { SubscriptionService } from "../server-services/subscription.service";
import { CordovaService } from "../services/cordova.service";
@Injectable({
  providedIn: "root",
})
export class MainPageGuard implements CanActivate {
  constructor(
    private accountService: AccountService,
    private router: Router,
    private routerHandler: RouterHandler,
    private dialogService: DialogService,
    private restApiService: ServerRestApiService,
    private dialog: MatDialog,
    private authService: AuthService,
    private subscriptionService: SubscriptionService
  ) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ):
    boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
    
    let fragment = {};

    let routerResponse = this.routerHandler.processUrl(
      state.url // do not use document.location, you can not get the right info from cordova webview
    );

    if (routerResponse) {
      fragment = routerResponse.routerResponse.fragment;
    }

    if (fragment["register-confirm"]) {
      let parse = this.router.parseUrl(
        "/register-confirm#register-confirm!" + fragment["register-confirm"]
      );
      return parse;
    } else if (fragment["recover-account"]) {
      return this.router.parseUrl(
        "/account-recovery-confirm#recover-account!" +
          fragment["recover-account"]
      );
    } else if (fragment["email-change"]) {
      var newEmailToken = fragment["email-change"];

      var editEmailPromise: Promise<boolean | UrlTree> = new Promise(
        (resolve) => {
          this.accountService
            .editEmail(newEmailToken)
            .then((res) => {
              this.dialogService.openAlertDialog(
                marker("Email change"),
                marker(
                  "Email changed successfully! Please log in with your new email."
                )
              );

              let loginNavigation = () => {
                this.restApiService.unsubscribeOnAuthCloseSubscribe(
                  loginNavigation
                );
                resolve(this.router.parseUrl("/login"));
              };

              this.restApiService.subscribeOnAuthCloseSubscribe(
                loginNavigation
              );
            })
            .catch((err) => {
              console.error("editEmail", err);
              this.dialogService.openAlertDialog(
                marker("Authentication Error"),
                marker("You must be logged in for this operation.")
              );
              resolve(false);
            });
        }
      );

      return editEmailPromise;
    }
    if (fragment["contact"]) {
      let event = () => {
        this.subscriptionService.unsubscribeWorkspaceLoaded(event);
        this.accountService
          .getAccount(fragment["contact"])
          .then((user) => {
            let ref = this.dialog.open(ContactDialogComponent, {
              data: user,
            });
            return ref.afterClosed();
          })
          .catch((err) => {
            this.dialogService.showSnackbar(marker("Could not found the user"));
            console.error("contact error", err);
          });
      };

      this.subscriptionService.subscribeWorkspaceLoaded(event);

      return true;
    }

    if (this.authService.isAnonym()) {
      return this.router.parseUrl("/login");
    } else return true;
  }
}
