import { Client } from 'cozy-client'
import { KONNECTORS_DOCTYPE, Konnector } from 'doctypes'

export default class KonnectorService {
  private _konnector: Konnector | null

  constructor(private _client: Client, private _konnectorId: string) {
    this._konnector = null
    this._client = _client
    this._konnectorId = _konnectorId
  }

  get konnector(): Konnector | null {
    return this._konnector
  }

  fetchKonnector = async () => {
    if (!(this._client && this._konnectorId)) {
      throw new Error(
        'KonnectorService : fetchKonnector - client or konnector id not found'
      )
    }
    try {
      const { data } = await this._client.query(
        this._client.find(KONNECTORS_DOCTYPE).where({
          _id: KONNECTORS_DOCTYPE + '/' + this._konnectorId,
        })
      )
      const konnector: Konnector = data && data[0]
      this._konnector = konnector
      return konnector
    } catch (error) {
      throw error
    }
  }

  async getKonnectorLastTrigger(slug: string) {
    const query = this._client
      .find('io.cozy.triggers')
      .where({ 'message.konnector': slug })
      .sortBy([{ 'cozyMetadata.updatedAt': 'desc' }])
      .limitBy(1)
    return await this._client.query(query)
  }

  async getKonnectorLastJob(slug: string) {
    const query = this._client
      .find('io.cozy.jobs')
      .where({ 'message.konnector': slug })
      // eslint-disable-next-line @typescript-eslint/camelcase
      .sortBy([{ finished_at: 'desc' }])
      .limitBy(1)
    return await this._client.query(query)
  }

  async getKonnectorLastStatus(): Promise<string | null> {
    if (!(this._client && this._konnectorId)) {
      throw new Error(
        'KonnectorService : findKonnector - client or konnector id not found'
      )
    }
    try {
      if (!this._konnector) {
        await this.fetchKonnector()
      }
      if (this._konnector) {
        const trigger = await this.getKonnectorLastTrigger(this._konnector.slug)
        if (trigger && trigger.current_state && trigger.current_state) {
          return trigger.current_state.status
        }
      }
      return null
    } catch (error) {
      throw error
    }
  }

  async isTriggerSetForKonnector(): Promise<boolean> {
    if (!(this._client && this._konnectorId)) {
      throw new Error(
        'KonnectorService : findKonnector - client or konnector id not found'
      )
    }
    try {
      if (!this._konnector) {
        await this.fetchKonnector()
      }
      if (this._konnector) {
        const trigger = await this.getKonnectorLastTrigger(this._konnector.slug)
        if (trigger) {
          return true
        }
      } else {
        return false
      }
      return false
    } catch (error) {
      throw error
    }
  }

  static createIndexKonnector = async (client: Client) => {
    const query = client
      .find('io.cozy.konnectors')
      // eslint-disable-next-line @typescript-eslint/camelcase
      .where({ _id: 'index' })
      .limitBy(1)
    return await client.query(query)
  }
}