import mongoose from 'mongoose';

import { IQuickbooksAccount } from '../models/QuickbooksAccount.model';

function convertNumberToString(obj: Object): Object {
  let newObj = {};
  for (const prop in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, prop)) {
      if (obj[prop] === null) {
        newObj[prop] = '';
      } else {
        newObj[prop] = (typeof obj[prop] === 'number') ? obj[prop].toString() : obj[prop];
      }
    }
  }
  return newObj;
}

export class IQuickbooksUploadItem implements IQuickbooksAccount {

  uiId: string = '';
  accountCode: string = '';
  fullName: string = '';
  description: string = '';
  companyId: mongoose.Types.ObjectId = null;

  constructor(
    item: Partial<IQuickbooksAccount>,
    options: { [extraOption: string]: string }
  ) {
    if (options && options.companyId) {
      item.companyId = new mongoose.Types.ObjectId(options.companyId);
    }
    item = convertNumberToString(item);
    Object.assign(this, item);
  }

  async initialize() {
    return await this.validateData();
  }

  async validateData() {
    const errors = [];

    if (!this.accountCode || this.accountCode.trim().length === 0) {
      errors.push({ accountCode: [{ error: `account code is too short` }] });
    }

    if (!this.fullName || this.fullName.trim().length === 0) {
      errors.push({ fullName: [{ error: `full name is too short` }] });
    }

    if (!this.companyId) {
      errors.push({ fullName: [{ error: `company is required` }] });
    }

    return errors;
  }

}
