import { Component, ChangeDetectionStrategy, AfterViewInit, ElementRef, ViewChild, Inject, Renderer2 } from '@angular/core';
import { Select, Store } from '@ngxs/store';
import { RemissionSelectors } from 'apps/sales/src/app/core/store/selectors/remission.selectors';
import { Observable, Subject } from 'rxjs';
import { ShippingDocument, RemissionProcess } from '@isa/remission';
import { RemissionTargetType } from '../../../models/remission-resource-type.model';
import { filter, map, take } from 'rxjs/operators';
import { isNullOrUndefined } from 'util';
import { UpdateShippingDocuent } from 'apps/sales/src/app/core/store/actions/remission.actions';
import { RemissionActiveView } from '../../../models';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-remission-shipping-document-container',
  templateUrl: './shipping-document-container.component.html',
  styleUrls: ['./shipping-document-container.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RemissionShippingDocumentContainerComponent implements AfterViewInit {
  @Select(RemissionSelectors.getRemissionProcess)
  currentRemissionProcess$: Observable<RemissionProcess>;
  @Select(RemissionSelectors.getRemissionShippingDocument)
  shippingDocument$: Observable<ShippingDocument>;
  @Select(RemissionSelectors.getRemissiontarget)
  currentRemissionTarget$: Observable<RemissionTargetType>;

  @ViewChild('shippingDocumentContainer')
  shippingDocumentContainer: ElementRef;

  constructor(private store: Store, private renderer: Renderer2, @Inject(DOCUMENT) private document: Document) {}

  ngAfterViewInit() {
    this.updateMinHeight();
  }

  updateShippingDocument() {
    this.currentRemissionProcess$
      .pipe(
        filter((process) => !isNullOrUndefined(process)),
        map((process) => process.id),
        take(1)
      )
      .subscribe((remissionProcessId) => this.store.dispatch(new UpdateShippingDocuent(remissionProcessId)));
  }

  updateMinHeight() {
    if (this.shippingDocumentContainer && this.document.body.clientHeight) {
      const height = this.document.body.clientHeight;

      this.renderer.setStyle(this.shippingDocumentContainer.nativeElement, 'min-height', `${height * 0.6}px`);
    }
  }
}
