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 { ImageStorage } from '../../../environments/server.config';


@Component({
  selector: 'app-currency-list',
  templateUrl: './currency-list.component.html',
  styleUrls: ['./currency-list.component.scss']
})
export class CurrencyListComponent implements OnInit {
  currencyList: any[];
  fname: any;
  lang =  'en';
  responseMsg: any;
  error: boolean;
  success: boolean;
  loader: boolean;

  constructor(private router: Router, private route: ActivatedRoute, public vs: ValidationService, public service: WebService) {
    this.responseMsg = '';
    this.error = false;
    this.success = false;
    this.loader = false;
  }

  ngOnInit() {
    this.getCurrency();
  }

  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);
  }

  reset() {
    this.error = false;
    this.success = false;
  }

  deleteClick(currency_id: any) {
    this.reset();
    const res = confirm('Do you want to remove this currency ?');
    if (res === true) {
      this.loader = true;
      this.fname = 'currency_delete';
      const post_data = {'currency_id': currency_id};
        this.service.post_data(this.fname, post_data).subscribe(response => {
          this.loader = false;
          console.log(response);
          if (response.code === 1) {
            this.success = true;
            console.log(this.success);
            this.getCurrency();
          } 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); */
  }

  editClick(id: number) {
    this.router.navigate(['maker/currency_edit/' + id]);
  }

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

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

  getImage(image_url) {
    return ImageStorage + image_url;
  }

}
