import { Component, ViewEncapsulation, ChangeDetectionStrategy, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ControlBaseComponent, FilterValue } from '../control-base.component';
import { FAST_KENDO_COMMON, FAST_PAGE_COMMON } from '../../app.config';
import { KENDO_BUTTONGROUP } from '@progress/kendo-angular-buttons';
import { HttpClient } from '@angular/common/http';
import { FilterControlService } from '../filter-control.service';

@Component({
  selector: 'control-buy-sell',
  templateUrl: './control-buy-sell.component.html',
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [CommonModule, FAST_PAGE_COMMON, FAST_KENDO_COMMON, KENDO_BUTTONGROUP]
})
export class ControlBuySellComponent extends ControlBaseComponent implements OnInit {
  http = inject(HttpClient);
  controlService = inject(FilterControlService);
  buyText = 'Buy Deals';
  sellText = 'Sell Deals';
  allText = 'All Deals';

  selectedItem: { name: string; selected?: boolean };

  items: Array<{ name: string; selected?: boolean }> = [
    { name: this.buyText },
    { name: this.sellText },
    { name: this.allText, selected: true }
  ]

  constructor() {
    super();
  }

  ngOnInit(): void {
    this.form = this.myFb.group({});
  }

  getValue(): string {
    return this.items[0].selected ? this.buyText : this.items[1].selected ? this.sellText : null;
  }

  getFilterValue(): FilterValue {
    const value1 = this.getValue();
    const preview = value1;
    const filterValue: FilterValue = { id: 0, name: this.parameterName, filterId: this.filterId, dataSourceId: this.dataSourceId, preview: preview, value1: value1, value2: null }
    return filterValue;
  }

  getPreview(): string {
    const preview: string = null;
    return preview;
  }

  setFilterValue(param: FilterValue) {
    if (param.value1 === this.buyText) {
      this.items[2].selected = false;
      this.items[0].selected = true;
    }
    else if (param.value1 === this.sellText) {
      this.items[2].selected = false;
      this.items[1].selected = true;
    }
    this.valueUpdated$.next(null);
    this.myRef.detectChanges();
  }

  resetValue() {
    this.items[0].selected = false;
    this.items[1].selected = false;
    this.items[2].selected = true;
    this.valueUpdated$.next(null);
    this.myRef.detectChanges();
  }

  selectedChange(newSelectedValue: boolean, item: { name: string; selected?: boolean }) {
    this.items.forEach(i => i.selected = false);
    item.selected = newSelectedValue;
    this.valueUpdated$.next(null);
  }
}
