import { BaseAction } from './base-action';
import { Observable, of } from 'rxjs';
import { QueryParamsHandling, Router } from '@angular/router';
import { IActionResult } from '../interfaces/actions/action-result';
import { ActionTypes } from '@objects-view/actions/action-types';
import { RouteHelper } from '@shared/ui-api/route-helper';

export class RouterLinkAction extends BaseAction {
  type = ActionTypes.RouterLinkAction;
  routerUrl: string;
  router: Router;
  queryParams = {};
  fragment?: string;
  queryParamsHandling?: QueryParamsHandling;

  constructor(init?: Partial<RouterLinkAction>) {
    super(init);
    this.displayMessages = false;
    this.refreshAfterExecute = false;
    // separate query params from url
    const queryParamsSeparatorIndex = this.routerUrl.indexOf('?');
    if (queryParamsSeparatorIndex > -1) {
      const queryParamsString = this.routerUrl.substr(queryParamsSeparatorIndex + 1);
      queryParamsString.split('&').forEach((part) => {
        const item = part.split('=');
        this.queryParams[item[0]] = decodeURIComponent(item[1]);
      });
      this.routerUrl = this.routerUrl.substr(0, queryParamsSeparatorIndex);
    }

    if (this.propagateQueryParams) {
      Object.assign(this.queryParams, RouteHelper.getQueryParams(this.router, this.propagateQueryParams));
    }

    // separate fragment from url
    const fragmentSeparatorIndex = this.routerUrl.indexOf('#');
    if (fragmentSeparatorIndex > -1) {
      const tempUrl = this.routerUrl;
      this.routerUrl = tempUrl.substr(0, fragmentSeparatorIndex);
      this.fragment = tempUrl.substr(fragmentSeparatorIndex + 1);
    }
  }

  executeImpl(): Observable<IActionResult> {
    return of(null);
  }
}
