import Client from "src/services/webClient/Client";
import FormRequest from "src/models/FormRequest";
import notify, {TypeMessage} from "src/mixins/notification";
import {ParseItem} from "src/models/models";

export default abstract class DefaultService<T extends FormRequest> {
  public client: Client<T>

  public constructor() {
    this.client = new Client<T>();
  }

  public handleErrors(response: any, resource: T) {
    if (response.status === 422) {
      for(let i = 0; i < response.data.length; i++) {
        console.log(response.data[i]);

        notify(`
        (Campo: ${this.translateFields(response.data[i].error, resource.parseNames)})
         ${response.data[i].field}`, TypeMessage.error);
      }
    }
  }

  private translateFields(fieldName: string, fieldsTranslation: ParseItem[]) {
    let translateField: string | boolean = false;

    fieldsTranslation.forEach(translationObject => {
      if (translationObject.fieldName === fieldName) {
        translateField = translationObject.translation;
      }
    });

    return translateField ? translateField : fieldName;
  }
}
