import {Component, ElementRef, Inject, OnChanges, OnInit, ViewChild} from '@angular/core';
import {EditComponent} from '../../../../public/baseComponent/edit/edit.component';
import {Dialog} from '../../../../public/dialog';
import {MAT_DIALOG_DATA, MatDialog, MatDialogConfig, MatDialogRef} from '@angular/material';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {Service as Srv, ServicesService} from '../../../../public/services/services.service';
import {Service} from 'ngx-jsonapi';
import 'rxjs/add/operator/debounceTime';
import {ServicePivots} from '../../../../public/services/servicePivots';
import {Request, RequestsService} from '../../../../public/services/requests.service';
import {AuthService} from '../../../../public/services/auth.service';


@Component({
  selector: 'app-address',
  templateUrl: './address.component.html',
  styleUrls: ['./address.component.scss']
})

export class AddressComponent extends EditComponent {
  form: FormGroup;
  addressCtrl = new FormControl('', Validators.required);
  serviceCtrl = new FormControl('', Validators.required);
  services;
  selectedServicePivots: ServicePivots[];
  filteredServices: Srv[];
  selectedServices = false;
  sumPrice: number;
  @ViewChild('serviceElement') serviceElement: ElementRef;
  submit: boolean;
  selectedReceiversIds: string[] = [];
  requests: Request;
  selectedIds: any[];


  constructor(private service: ServicesService,
              private requestService: RequestsService,
              protected  dialog: Dialog,
              public  dialogRef: MatDialogRef<AddressComponent>,
              private fb: FormBuilder,
              private router: Router,
              private dialog2: MatDialog,
              private auth: AuthService,
  ) {
    super();
    console.log('zarha', this.service);
    console.log('amiri', this.requestService);
    this.selectedIds = [];
    this.requests = this.requestService.new();
    this.submit = false;
    this.selectedServicePivots = [];
    this.form = this.fb.group({
      addressCtrl: this.addressCtrl,
      serviceCtrl: this.serviceCtrl,
    });
    this.serviceCtrl.valueChanges
      .debounceTime(400)
      .subscribe(word => {
        this._filterInput(this.service, word);
      });
  }

  _filterInput(service: Service, value: string, key: string = 'name') {
    const remotefilter = {};
    remotefilter[key] = value;
    service.all({
      remotefilter: remotefilter,
      // page: {number: 1, size: 5}
    }).subscribe(data => {
      if (data.$source !== 'server' || data.$is_loading) {
        return;
      }

      // this.filteredOptions[key] = data.$toArray;
      this.filteredServices = <Srv[]>data.$toArray;
      // remove selected from filtered
      for (let i = 0; i < this.filteredServices.length; i++) {
        // for rooye selected ha
        for (let j = 0; j < this.selectedServicePivots.length; j++) {
          if (this.filteredServices[i].id === this.selectedServicePivots[j].id) {
            // must remove key2 index from selected
            this.filteredServices.splice(i, 1);
          }
        }
      }
      //
    });
  }

  resourceSelected(resource_id: string, resource_name: string): void {
//  age idesh vojod nadasht ezafe kon baray ersal be server ino mikhaim
    if (this.selectedReceiversIds.indexOf(resource_id) === -1) {
      this.selectedReceiversIds.push(resource_id);
      this.serviceCtrl.setValue(resource_name);
    }
    if (this.serviceElement.nativeElement.value = '') {
      this.serviceCtrl.setValue(null);
    }
  }

  Onsubmit() {
    this.requests.setLat(this.auth.currentUser.value['attributes']['lat']);
    this.requests.setLng(this.auth.currentUser.value['attributes']['lng']);
    this.requests.setAddress(this.form.controls['addressCtrl'].value);
    this.requests.setSumPrice(this.sumPrice);
    for (let i = 0; i < this.selectedServicePivots.length; i++) {
      const t = this.selectedServicePivots[i]['id'];
      this.selectedIds.push(t);
      console.log('salam', typeof t);
      // this.requests.setServicesWithIds()
      //  this.requests.addRelationship(this.selectedServicePivots[i]['id'] , 'services' );
    }
    console.log('selecteed', this.selectedIds);
    this.requests.setServicesWithIds(this.selectedIds);
    this.requests.setTypeWithId('1');
this.requests.setServicePivots(this.selectedServicePivots);
    this.requests.save({}, () => {
      console.log('anjam shod');
    }, (error) => {
      console.log('error dare', error);
    });
    console.log('zarhaAmiri', this.requests);
  }

  Exit() {
    this.dialog.closeAll();
  }

  inc(servicePivots: ServicePivots) {
    servicePivots.num++;
    this.calcSumPrices();
  }

  dec(servicePivots: ServicePivots) {
    if (servicePivots.num <= 0) {
      return servicePivots.num = 1;
    }
    servicePivots.num--;
    this.calcSumPrices();
  }

  calcSumPrices() {
    this.sumPrice = 0;
    for (let i = 0; i < this.selectedServicePivots.length; i++) {
      this.sumPrice += this.selectedServicePivots[i].num * this.selectedServicePivots[i].price;
    }
  }

  newServiceSelected(id: String, name: String, price: number) {
    this.selectedServices = true;
    const servicePivots = new ServicePivots(id, name, price, 1);
    this.selectedServicePivots.push(servicePivots);
    this.calcSumPrices();
    // todo
    this.submit = true;
  }

}
