import {Dialog} from './dialog';
import {ICollection, Resource} from 'ngx-jsonapi';
import {Service, Service as Srv, ServicesService} from '../components/basic/services/services.service';
import {Base} from 'ngx-jsonapi/services/base';
import {Product, ProductsService} from '../components/basic/products/products.service';

export function setErrors(errors: any[], controls, dialog: Dialog) {
  let errorStrings: string[] = [];
  for (const key in errors) {
    const err = errors[key];
    let errorKey = '';
    try {
      errorKey = (err.source.pointer).split('\/').reverse()[0] + 'Ctrl';
    } catch (e) {
      errorKey = '';
    }
    if (errorKey !== '') {
      // ERRPR KEY HAMON INDEX HAST
      controls[errorKey].setErrors({'error': err.detail});
    } else {
      errorStrings[errorStrings.length] = err.detail;
    }
  }
  if (errorStrings.length > 0) {
    dialog.openForAlert(errorStrings.join(','));
  }
}

// az server username barmigardone
export function repairErrors(errors) {
  for (const key in errors) {
    if (errors[key]['source'] && (errors[key]['source']['pointer'] == '/data/attribute/email' || errors[key]['source']['pointer'] == '/data/attribute/mobile')) {
      errors[key]['source']['pointer'] = '/data/attribute/username';
    }
  }
  return errors;
}

export function getBaseServices(): Service[] {
  const basics = JSON.parse(localStorage.getItem('basics'));
  const basicServicess = JSON.parse(basics['services']);
  const resource: ICollection<Srv> = Base.newCollection<Srv>();
  (new ServicesService()).convert(basicServicess, resource);
  return resource.$toArray;
}

export function getBaseProduct(): Product[] {
  const basics = JSON.parse(localStorage.getItem('basics'));
  const basicProducts = JSON.parse(basics['products']);
  // todo in porside shavad
  const resource: ICollection<Product> = Base.newCollection<Product>();
  (new ProductsService()).convert(basicProducts, resource);
  return resource.$toArray;
}
