import type { IObservableArray } from 'mobx';
import { makeAutoObservable, observable, reaction } from 'mobx';
import type { Status } from 'ui/elements/types';

import type RootStore from 'stores/root';
import Validation from '../../validation';
import type { ValidationParams } from '../../validation/types';
import type { Row } from './types';

export default class PaymentsTable {
  root: RootStore;
  validation: Validation;
  values: IObservableArray<number>;
  statuses: IObservableArray<Status>;

  constructor(rootStore: RootStore) {
    this.validation = new Validation({
      err_key: 'ERR_PAYMENTS_TABLE',
      err_title: 'Таблица платежей',
    });

    this.values = observable<number>([]);
    this.statuses = observable<Status>([]);

    makeAutoObservable(this);
    this.root = rootStore;

    /**
     * Синхронизируем длину массива значений и статусов
     */
    reaction(
      () => this.values.length,
      (length) => {
        this.statuses.length = length;
      }
    );
  }

  getValue(index: number) {
    return this.values[index];
  }

  setValue = (index: number, value: number) => {
    this.values[index] = value;
  };

  setValues = (values: number[]) => {
    this.values.replace(values);
  };

  getStatus(index: number) {
    return this.statuses[index];
  }

  setStatus = (index: number, status: Status) => {
    this.statuses[index] = status;
  };

  setStatuses = (statuses: Status[]) => {
    this.statuses.replace(statuses);
  };

  setRow = (index: number, row: Row) => {
    this.setValue(index, row.value);
    this.setStatus(index, row.status);
  };

  setRows = (rows: Row[]) => {
    const values = rows.map((row) => row.value);
    const statuses = rows.map((row) => row.status);

    this.setValues(values);
    this.setStatuses(statuses);
  };

  validate = ({ invalid, message }: ValidationParams) => {
    if (invalid) {
      this.validation?.addError(message);
    } else {
      this.validation?.removeError(message);
    }
  };

  reset = () => {
    this.values.clear();
    this.statuses.clear();
    this.validation.clearErrors();
  };
}
