import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { WebService } from './../../providers/web.service';
import { ValidationService } from './../../providers/validation.service';
import { FormGroup, FormArray, FormBuilder, Validators } from '@angular/forms';


@Component({
  selector: 'app-currency',
  templateUrl: './currency.component.html',
  styleUrls: ['./currency.component.scss']
})
export class CurrencyComponent implements OnInit {
  currencyList: any[];
  avaliableList: any[];
  fname: any;
  lang =  'en';
  responseMsg: any;
  error: boolean;
  success: boolean;
  loader: boolean;
  buffer: any[];
  packet: any[];
  selectedList: any[];
  public currencyForm: FormGroup;
  loginDetails: any;
  currenySubmit: boolean;
  userDetails: any;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    public vs: ValidationService,
    public service: WebService,
    private fb: FormBuilder
  ) {
    this.currencyForm = this.fb.group({
      'provider_id': ['', Validators.compose([Validators.required])],
      'currency': this.fb.array([])
    });
    this.responseMsg = '';
    this.error = false;
    this.success = false;
    this.loader = false;
    this.buffer = [];
    this.packet = [];
    this.selectedList = [];
    this.currencyList = [];
    this.currenySubmit = false;
    this.loginDetails = JSON.parse(this.service.getLocalStorageItem('userData'));
    this.getProvider();
  }

  ngOnInit() {
    this.getCurrency();
    const This = this;
    setTimeout(function() {
      This.getunique(This.currencyList, This.selectedList);
    }, 2000);
  }

  goToPage(path, data = null) {
    console.log(data);
    this.router.navigateByUrl(path, { queryParams: data});
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }

  getCurrency() {
    this.loader = true;
    this.fname = 'currency';
      this.service.post_data(this.fname,[]).subscribe(response => {
        this.loader = false;
        console.log(response);
        if (response.code === 1) {
          this.currencyList = response.responseResult;
        } else {
          this.error = true;
          this.responseMsg = this.vs.errorCode[this.lang][response.errorCode];
        }
      }, (error) => {
        this.error = true;
        this.responseMsg =  this.vs.errorCode[this.lang]['ER08'];
    });

    const This = this;
    setTimeout(function() {
      This.responseMsg = '';
    }, 3000);
  }

  providerCurrency(provider_id: any) {
      this.loader = true;
      this.fname = 'forex_currency';
      const post_data = {'provider_id': provider_id};
        this.service.post_data(this.fname, post_data).subscribe(response => {
          this.loader = false;
          console.log(response);
          if (response.code === 1) {
            this.selectedList = response.responseResult;
            this.patchValues();
          } else {
            this.selectedList = [];
          }
        }, (error) => {
          // this.error = true;
          // this.responseMsg =  this.vs.errorCode[this.lang]['ER08'];
      });
      const This = this;
      setTimeout(function() {
        This.responseMsg = '';
      }, 3000);
  }

  currency_add(curr: any) {
    if (!this.buffer.filter(function(elem) {
      return elem.id === curr.id;
    }).length) {
      this.buffer.push(curr);
    }
    console.log(this.buffer);
  }

  currency_remove(curr: any) {
    if (!this.packet.filter(function(elem) {
      return elem.id === curr.id;
    }).length) {
      this.packet.push(curr);
    }
    console.log(this.packet);
  }

  currency_push() {
    if (this.selectedList.length === 0) {
      this.selectedList = this.buffer;
    } else {
      Array.prototype.push.apply(this.selectedList, this.buffer);
    }
    this.buffer = [];
    this.patchValues();
    this.getunique(this.currencyList, this.selectedList);
  }

  currency_pop() {
    this.selectedList = this.selectedList.filter(this.comparer(this.packet));
    this.packet = [];
    this.getunique(this.currencyList, this.selectedList);
    this.patchValues();
  }

  getunique(allList, ArrayList) {
    console.log(allList, ArrayList);
    this.avaliableList = allList.filter(this.comparer(ArrayList));
    console.log(this.avaliableList);
  }

  comparer(otherArray) {
    return function(current) {
      return otherArray.filter(function(other){
        return other.id === current.id;
      }).length === 0;
    };
  }

  get formData() { return <FormArray>this.currencyForm.get('currency'); }

  patchValues() {
    console.log('called');
    console.log(this.selectedList);
     const currencyCtrl = <FormArray>this.currencyForm.controls['currency'];
     currencyCtrl.controls = [];
    const currencyCount = this.selectedList.length;
    console.log(currencyCount);
    let currency_details;
      for (let i = 0; i < currencyCount; i++) {
        console.log();
         currency_details = {
          'currency_id': this.selectedList[i].id,
          'rate': [this.selectedList[i].rate, Validators.compose([Validators.required ])]
        };
        currencyCtrl.push(this.fb.group(currency_details));
      }
    }

    currency_assign() {
      this.currenySubmit = true;
      const This = this;
      if (this.currencyForm.valid) {
        this.loader = true;
        const postData = this.currencyForm.value;
        console.log(postData);

        this.fname = 'currency_assign';
        this.service.post_data(this.fname, postData).subscribe(response => {
          this.loader = false;
          if (response.code === 1) {
            this.success = true;
            this.currenySubmit = false;
          } else {
            this.error = true;
            this.responseMsg = this.vs.errorCode[this.lang][response.errorCode];
          }
        }, (error) => {
          this.error = false;
          this.responseMsg = this.vs.errorCode[this.lang]['ER08'];
        });
      }
    }

    getProvider() {
      this.fname = 'get_user_details';
      const post_data = {'user_id': this.loginDetails.user_id};
      this.service.post_data(this.fname, post_data).subscribe(response => {
        if (response.code === 1) {
          this.userDetails = response.responseResult;
          this.currencyForm.controls['provider_id'].setValue(this.userDetails.id);
          this.providerCurrency(this.userDetails.id);
        } else {
          this.error = true;
          this.responseMsg = this.vs.errorCode[this.lang][response.errorCode];
        }
      }, (error) => {
        this.error = true;
        this.responseMsg =  this.vs.errorCode[this.lang]['ER08'];
    });
    }

    logout() {
      this.service.logout();
    }

    cancelClick() {
      this.router.navigate(['/forex']);
    }

    CheckClass(id, type: any) {
      let state = false;
      if (type === 'add') {
        for (let i = 0, len = this.buffer.length; i < len; i++) {
          console.log(this.buffer[i].id);
          if (this.buffer[i].id === id) {
            state = true;
          }
        }
        return state;
      }

      if (type === 'remove') {
        for (let i = 0, len = this.packet.length; i < len; i++) {
          console.log(this.packet[i].id);
          if (this.packet[i].id === id) {
            state = true;
          }
        }
        return state;
      }

    }



}
