import { Injectable } from '@angular/core';
import { BranchQueryTokenDTO, StoreCheckoutService, BranchDTO } from '@swagger/checkout';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { isNullOrUndefined } from 'util';
import { OrderService } from '@swagger/oms';
import { SsoService } from 'sso';

@Injectable({
  providedIn: 'root',
})
export class BranchService {
  constructor(private checkoutService: StoreCheckoutService, private orderService: OrderService, private ssoService: SsoService) {}

  getCurrentBranchNumber() {
    return this.ssoService.getClaimByKey('branch_no');
  }

  searchBranches(input: string, skip: number, take: number): Observable<BranchDTO[]> {
    const params = <StoreCheckoutService.StoreCheckoutQueryBranchesParams>{
      queryToken: <BranchQueryTokenDTO>{
        input: { qs: input },
        skip: skip,
        take: take,
      },
    };
    return this.checkoutService.StoreCheckoutQueryBranches(params).pipe(
      map((response) => {
        if (response.error) {
          throw new Error(response.message);
        }
        return response.result;
      }),
      map((branches) => {
        return branches && branches.length > 0
          ? branches.filter((branch) => {
              if (
                branch &&
                !isNullOrUndefined(branch.isOnline) &&
                branch.isOnline &&
                !isNullOrUndefined(branch.isShippingEnabled) &&
                branch.isShippingEnabled &&
                !isNullOrUndefined(branch.isOrderingEnabled) &&
                branch.isOrderingEnabled
              ) {
                return true;
              } else {
                return false;
              }
            })
          : null;
      })
    );
  }

  async getOrderBranchList() {
    return this.orderService
      .OrderGetBranches({})
      .pipe(
        map((response) => {
          if (response.error) {
            throw new Error(response.message);
          }
          return response.result;
        })
      )
      .toPromise();
  }
}
