import { HttpClient } from '@angular/common/http'
import { Injectable } from '@angular/core'
import { Observable } from 'rxjs'
import { Collection } from '../viya-api-explorer/models/collection.model'
import { AppStoreService } from './app-store.service'
import { ViyaApis } from '../viya-api-explorer/models/viya-apis.models'

@Injectable({
  providedIn: 'root'
})
export class SasViyaService {
  // Viya APIs
  public viyaApis: ViyaApis = {
    Analytics_Insights: {
      insights: '/insights'
    },
    Visualisation: {
      reports: '/reports',
      reportImages: '/reportImages',
      reportTransforms: '/reportTransforms',
      visualAnalytics: '/visualAnalytics'
    },
    Compute: {
      jobs: '/jobDefinitions',
      jobExecution: '/jobExecution'
    },
    Decision_Management: {
      modelManagement: '/modelManagement',
      modelRepository: '/modelRepository',
      modelPublish: '/modelPublish',
      microanalyticScore: '/microanalyticScore',
      dataMining: '/dataMining',
      businessRules: '/businessRules',
      referenceData: '/referenceData',
      treatmentDefinitions: '/treatmentDefinitions',
      subjectContacts: '/subjectContacts',
      decisionsRuntimeBuilder: '/decisionsRuntimeBuilder'
    },
    Core_Services: {
      folders: '/folders',
      files: '/files',
      annotations: '/annotations',
      authorization: '/authorization',
      relationships: '/relationships',
      SASLogon: '/SASLogon'
    },
    Automated_Machine_Learning: {
      mlPipelineAutomation: '/mlPipelineAutomation'
    },
    Other: {
      identities: '/identities'
    }
  }

  private serverUrl: string = ''

  constructor(
    private http: HttpClient,
    private appStoreService: AppStoreService
  ) {
    const adapterConfig = this.appStoreService.getDcAdapterSettings()

    this.serverUrl = adapterConfig?.serverUrl || ''

    //example
    this.getByCollection('jobs').subscribe((res) => {
      console.log('res', res)
    })
  }

  /**
   *
   * @returns All Viya API collections that we support
   */
  getAllCollections() {
    return this.viyaApis
  }

  /**
   * Used for clicking trough collections / apis
   * @param url collection/api endpoint url
   * @returns
   */
  getByUrl(url: string): Observable<Collection> {
    return this.http.get<Collection>(`${this.serverUrl}${url}`, {
      withCredentials: true
    })
  }

  /**
   * We refer collection as starting point /jobs /folders etc.
   * @param apiCollection
   * @returns
   */
  getByCollection(apiCollection: string): Observable<Collection> {
    return this.http.get<Collection>(`${this.serverUrl}${apiCollection}`, {
      withCredentials: true
    })
  }
}
