import { Component, OnInit, ViewChild } from '@angular/core';
import { SearchInputComponent } from '@libs/ui';
import { Store } from '@ngxs/store';
import { BranchSelectors } from 'apps/sales/src/app/core/store/selectors/branch.selector';
import { GoodsInService } from 'apps/sales/src/app/core/services/goods-in.service';
import { take } from 'rxjs/operators';
import { OrderItemListItemDTO } from '@swagger/oms';
import {
  SetGoodsInOrders,
  SetGoodsInCachedOrders,
  ClearGoodsInCachedOrders,
  SetGoodsInSearch,
  SetGoodsInUseCache,
} from 'apps/sales/src/app/core/store/actions/goods-in.actions';
import { AddBreadcrumb } from 'apps/sales/src/app/core/store/actions/breadcrumb.actions';
import { SetBranchProcessCurrentPath } from 'apps/sales/src/app/core/store/actions/branch-process.actions';
import { Router } from '@angular/router';
import { GOODS_IN_SCROLL_INDEX } from 'apps/sales/src/app/core/utils/app.constants';

@Component({
  selector: 'app-goods-in-search',
  templateUrl: './goods-in-search.component.html',
  styleUrls: ['./goods-in-search.component.scss'],
})
export class GoodsInSearchComponent implements OnInit {
  @ViewChild('searchInput')
  searchInput: SearchInputComponent;
  error: string;
  constructor(private store: Store, private goodsInService: GoodsInService, private router: Router) {}

  ngOnInit() {
    this.initialize();
  }

  search(input: string) {
    const branchNo = this.store.selectSnapshot(BranchSelectors.getUserBranch);
    this.goodsInService
      .search(input, 0, 10)
      .pipe(take(1))
      .subscribe((data) => this.searchResultHandler(data, input, branchNo));
  }

  initialize() {
    this.store.dispatch(new ClearGoodsInCachedOrders());
  }

  searchResultHandler(data: { results: OrderItemListItemDTO[]; hits: number }, input: string, branchNo: string) {
    if (data && data.results && data.results.length > 0) {
      this.error = null;
      this.searchInput.stopLoading();
      this.store.dispatch(new SetGoodsInOrders(data.results));
      this.store.dispatch(new SetGoodsInCachedOrders({ results: data.results, hits: data.hits }));
      this.store.dispatch(new SetGoodsInSearch({ input: input, branchnumber: branchNo }));
      this.store.dispatch(new SetGoodsInUseCache(true));
      sessionStorage.removeItem(GOODS_IN_SCROLL_INDEX);
      if (data.results.length === 1) {
        const item = data.results[0];
        this.navigate(`/goodsin/details/${item.orderId}/${item.orderItemId}/${item.processingStatus}`, item.product.name);
      } else {
        this.navigate('/goodsin/results', `${input} (${data.hits} Ergebnisse)`);
      }
    } else {
      this.searchInput.stopLoading();
      this.store.dispatch(new ClearGoodsInCachedOrders());
      this.error = 'Ergibt keine Suchergebnisse';
    }
  }

  navigate(path: string, name: string) {
    this.store.dispatch(
      new AddBreadcrumb(
        {
          name,
          path,
        },
        'goodsin'
      )
    );
    this.store.dispatch(new SetBranchProcessCurrentPath(path));
    this.router.navigate([path]);
  }
}
