import { Injectable } from '@angular/core';
import { StorageService } from 'src/app/core/services/storage.service';
import { Projects } from '../models/project';
import { StoreInstanceService } from './store-instance.service';
const initialState = {
  documents: [] as Projects[],
  listViewTwo: [] as Projects,
  listViewThree: [] as any,
  setupDocuments: [],
  details: [],
};

@Injectable({
  providedIn: 'root',
})
export class DocumentStore extends StoreInstanceService<typeof initialState> {
  constructor(public storage: StorageService) {
    super(initialState);
    if (this.storage.getObject('znak'))
      this.setupDocuments(this.storage.getObject('documents_setup'));
  }

  public setDocuments(data: any) {
    this.update((state) => {
      return {
        ...state,
        documents: data,
        listViewTwo: data,
        listViewThree: data,
      };
    });
  }

  public setupDocuments(data: any) {
    this.update((state) => {
      return {
        ...state,
        setupDocuments: data,
      };
    });
  }

  public setDetails(data: any) {
    this.update((state) => {
      return {
        ...state,
        details: data,
      };
    });
  }

  public resetStoreCotations() {
    this.update((state: any) => {
      return {
        ...state,
        documents: [],
        listViewTwo: [],
        listViewThree: [],
        setupCotations: [],
        details: [],
      };
    });
  }

  public addNewRecordData(data: any) {
    this.update((state: any) => {
      return {
        ...state,
        documents: [data].concat(state.documents),
      };
    });
  }

  public updateDocuments(data: any, id: string) {
    this.update((state: any) => {
      return {
        ...state,
        documents: this.checkEdit(state.documents, data, id),
      };
    });
  }

  private checkEdit(project: any, data: any, id: string) {
    const response = project.map((res: any) => {
      if (res.notesid === id) {
        res = data;
      }

      return res;
    });

    return response;
  }

  public removeDocuments(data: any) {
    this.update((state: any) => {
      return {
        ...state,
        documents: state.documents.filter(
          (item: Projects) => !data.includes(item.notesid)
        ),
      };
    });
  }

  public editMass(data: any) {
    this.update((state: any) => {
      return {
        ...state,
        documents: this.updateMultipleCheck(state.documents, data),
      };
    });
  }

  public updateMultipleCheck(old_version: any, new_version: any) {
    const real_new = old_version.map((el: any) => {
      var found = new_version.find(
        (s: any) => el['notesid'] !== '' && s['notesid'] === el['notesid']
      );

      if (found) {
        el = Object.assign(el, found);
      }
      return el;
    });

    return real_new;
  }
}
