import hash from 'object-hash';
import { pullFromCache, pushToCache } from '~/cache/api';
import { JoinRequestListPaginationController } from './JoinRequestListPaginationController';
import { JoinRequestListQueryStreamController } from './JoinRequestListQueryStreamController';
import { LiveCollectionController } from '~/core/liveCollection/LiveCollectionController';
import { sortByFirstCreated, sortByLastCreated } from '~/core/query';
import { prepareCommunityJoinRequestPayload } from '~/communityRepository/utils';
import { EnumJoinRequestAction } from './enum';
import { isNonNullable } from '~/utils';
import { joinRequestLinkedObject } from '~/utils/linkedObject/joinRequestLinkedObject';
import {
  onJoinRequestCreated,
  onJoinRequestDeleted,
  onJoinRequestUpdated,
} from '~/communityRepository/joinRequest/events/';
import { onLocalCommunityJoin } from '~/communityRepository/communityMembership';

export class JoinRequestListLiveCollectionController extends LiveCollectionController<
  'joinRequest',
  Amity.JoinRequestListLiveCollection,
  Amity.JoinRequest,
  JoinRequestListPaginationController
> {
  private queryStreamController: JoinRequestListQueryStreamController;

  private query: Amity.JoinRequestListLiveCollection;

  constructor(
    query: Amity.JoinRequestListLiveCollection,
    callback: Amity.LiveCollectionCallback<Amity.JoinRequest>,
  ) {
    const queryStreamId = hash(query);
    const cacheKey = ['joinRequestList', 'collection', queryStreamId];
    const paginationController = new JoinRequestListPaginationController(query);

    super(paginationController, queryStreamId, cacheKey, callback);

    this.query = query;
    this.queryStreamController = new JoinRequestListQueryStreamController(
      this.query,
      this.cacheKey,
      this.notifyChange.bind(this),
      prepareCommunityJoinRequestPayload,
    );

    this.callback = callback.bind(this);
    this.loadPage({ initial: true });
  }

  protected setup() {
    const collection = pullFromCache<Amity.JoinRequestListLiveCollectionCache>(this.cacheKey)?.data;

    if (!collection) {
      pushToCache(this.cacheKey, {
        data: [],
        params: this.query,
      });
    }
  }

  protected async persistModel(queryPayload: Amity.CommunityJoinRequestPayload & Amity.Pagination) {
    await this.queryStreamController.saveToMainDB(queryPayload);
  }

  protected persistQueryStream({
    response,
    direction,
    refresh,
  }: Amity.LiveCollectionPersistQueryStreamParams<'joinRequest'>) {
    const joinRequestResponse = response as unknown as Amity.CommunityJoinRequestPayload &
      Partial<Amity.Pagination>;
    this.queryStreamController.appendToQueryStream(joinRequestResponse, direction, refresh);
  }

  startSubscription() {
    return this.queryStreamController.subscribeRTE([
      { fn: onJoinRequestCreated, action: EnumJoinRequestAction.OnLocalJoinRequestCreated },
      { fn: onJoinRequestUpdated, action: EnumJoinRequestAction.OnLocalJoinRequestUpdated },
      { fn: onJoinRequestDeleted, action: EnumJoinRequestAction.OnLocalJoinRequestUpdated },
      {
        fn: onLocalCommunityJoin,
        action: EnumJoinRequestAction.OnLocalJoinRequestUpdated,
      },
    ]);
  }

  notifyChange({ origin, loading, error }: Amity.LiveCollectionNotifyParams) {
    const collection = pullFromCache<Amity.JoinRequestListLiveCollectionCache>(this.cacheKey)?.data;

    if (!collection) return;

    const data = this.applyFilter(
      collection.data
        .map(id => pullFromCache<Amity.InternalJoinRequest>(['joinRequest', 'get', id])!)
        .filter(isNonNullable)
        .map(({ data }) => data)
        .map(joinRequestLinkedObject),
    );

    if (!this.shouldNotify(data) && origin === 'event') return;

    this.callback({
      onNextPage: () => this.loadPage({ direction: Amity.LiveCollectionPageDirection.NEXT }),
      data,
      hasNextPage: !!this.paginationController.getNextToken(),
      loading,
      error,
    });
  }

  applyFilter(data: Amity.JoinRequest[]) {
    let joinRequest = data;

    if (this.query.communityIds && this.query.communityIds.length > 0) {
      joinRequest = joinRequest.filter(joinRequest =>
        this.query.communityIds.some(id => id === joinRequest.targetId),
      );
    }

    const sortFn = (() => {
      switch (this.query.sortBy) {
        case 'firstCreated':
          return sortByFirstCreated;
        case 'lastCreated':
          return sortByLastCreated;
        default:
          return sortByLastCreated;
      }
    })();

    joinRequest = joinRequest.sort(sortFn);

    return joinRequest;
  }
}
