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 { FormControl, FormGroup, FormBuilder, Validators, ValidationErrors } from '@angular/forms';
import { ImageStorage } from '../../../environments/server.config';

@Component({
  selector: 'app-currency-edit',
  templateUrl: './currency-edit.component.html',
  styleUrls: ['./currency-edit.component.scss']
})
export class CurrencyEditComponent implements OnInit {
  currencyForm: FormGroup;
  mobnumPattern = '^((\\+?)|0)?[0-9]{8,15}$';
  emailPattern = '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$';
  currencySubmit: boolean;
  lang =  'en';
  error_msg: any[];
  funcName: any;
  loader: boolean;
  responseError: any;
  error: boolean;
  success: boolean;
  file: File;
  currency: any;
  image_url: any;
  curr_id: any;

  constructor(private router: Router,
    private route: ActivatedRoute,
    public vs: ValidationService,
    public service: WebService,
    private formBuilder: FormBuilder
    ) {
      this.loader = false;
      this.error = false;
      this.success = false;
      this.currencySubmit = false;
      this.error_msg = this.vs.errorList[this.lang];
    }

    ngOnInit() {
      const parm = decodeURIComponent(this.route.snapshot.params['id']);
    // tslint:disable-next-line:radix
      const id = parseInt(parm);
      this.curr_id = id;
      this.getCurrency(id);
      this.currencyForm = this.formBuilder.group({
        'name':  ['', Validators.compose([Validators.required])],
        'symbol':  ['', Validators.compose([Validators.required])],
        'flag':  [''],
        'rate':  ['', Validators.compose([Validators.required])],
        'start_from':  ['', Validators.compose([Validators.required])],
        'id': [id]
      });
    }

    onFileChange(event) {
      if (event.target.files.length > 0) {
          this.file = event.target.files[0];
      }
      console.log(this.file);
  }

  currencyProcess() {
      const This = this;
      this.error = false;
      this.success = false;
      console.log(this.currencyForm.value);
      this.currencySubmit = true;
      if (this.currencyForm.valid) {
        this.loader = true;
        const providerObj = this.currencyForm.value;
        const post_data = this.prepareSave(providerObj);
        this.funcName = 'currency_edit';
        this.service.post_data(this.funcName, post_data).subscribe(response => {
          this.loader = false;
          console.log(response);
          if (response.code === 1) {
            console.log(post_data);
            this.success = true;
            this.currencySubmit = false;
            this.getCurrency(this.curr_id);
          } else {
            this.error = true;
            this.responseError = this.vs.errorCode[this.lang][response.errorCode];
          }
        }, (error) => {
          this.error = false;
          this.responseError = this.vs.errorCode[this.lang]['ER08'];
        });
      }
      console.log('tested');
    }

    prepareSave(formHasImage): any {
      const input = new FormData();
      if (this.file) {
        input.append('flag', this.file);
      }
      input.append('name', formHasImage.name);
      input.append('symbol', formHasImage.symbol);
      input.append('rate', formHasImage.rate);
      input.append('start_from', formHasImage.start_from);
      input.append('id', formHasImage.id);
      console.log(input);
      return input;
    }

    getCurrency(id) {
      console.log(id);
      this.loader = true;
      this.funcName = 'currency_details';
      const post_data = {'currency_id': id};
      this.service.post_data(this.funcName, post_data).subscribe(response => {
        this.loader = false;
        console.log(response);
        if (response.code === 1) {
          this.currency = response.responseResult;
          console.log(this.currency);
          this.image_url = this.currency.flag;
          this.currencyForm.patchValue({
            name: this.currency.name,
            symbol: this.currency.symbol,
            rate: this.currency.rate,
            start_from: this.currency.start_from,
            flag: ''
          });
        } else {
          this.error = true;
          this.responseError = this.vs.errorCode[this.lang][response.errorCode];
        }
      }, (error) => {
        this.error = true;
        this.responseError =  this.vs.errorCode[this.lang]['ER08'];
    });

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

    getImage() {
      return ImageStorage + this.image_url;
    }

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

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

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

}
