import { action, makeObservable, observable } from 'mobx';
import { TypeTags } from '../types/default';
import { Entity, EntityStore } from './EntityStore';
import { RootStore } from './RootStore';
import { loadable } from './Decorators/LoadingDecorator';
import request from '../services/request';

type TagRecord = TypeTags;

export class Tags extends Entity {
  @observable private tagRecord: TagRecord;

  constructor(_id: string, tagRecord: TagRecord) {
    super(_id);
    this.tagRecord = tagRecord;
  }

  get _tagRecord(): any {
    return this.tagRecord;
  }

  @action
  setTagRecord = (value: TagRecord): void => {
    this.tagRecord = value;
  };
}

export class TagsStore extends EntityStore<Tags> {
  constructor(private readonly rootStore: RootStore) {
    super();
    makeObservable(this);
  }

  @loadable
  async fetchGroupsList(url: string): Promise<void> {
    await request({
      method: 'get',
      url,
    }).then(
      action((response: any) => {
        this.entities.clear();
        for (const item of response.data.results) {
          const tag = new Tags(item.id, item);
          tag.setTagRecord(item);
          this.entities.set(item.id, tag);
        }
        this.setTotalGroups(response.data.count);
      }),
    );
  }

  @loadable
  async postRecordInGroupsList(url: string, data: TagRecord): Promise<void> {
    await request({
      method: 'post',
      url: url,
      data,
    }).then(
      action((response: any) => {
        const tag = new Tags(response.data.id, response.data);
        tag.setTagRecord(response.data);
        this.entities.set(response.data.id, tag);
      }),
    );
  }

  @loadable
  async patchRecordInGroupsList(
    url: string,
    data: TagRecord,
    id: number,
  ): Promise<void> {
    await request({
      method: 'patch',
      url: `${url}${id}/`,
      data,
    }).then(
      action((response) => {
        const newRecord = new Tags(response.data.id, response.data);
        this.entities.set(newRecord.id as any, newRecord);
      }),
    );
  }

  @loadable
  async deleteRecordInGroupsList(url: string, id: number[]): Promise<void> {
    const myPromise = (idd: number): Promise<number> => {
      return new Promise((resolve, reject) => {
        return request({
          method: 'delete',
          url: `${url}${idd}/`,
        })
          .then(() => resolve(idd))
          .catch(() => reject(idd));
      });
    };

    const mas = id.map((item) => {
      return myPromise(item);
    });

    await Promise.allSettled(mas);
  }
}
