import { type RouteLocation } from 'vue-router'
import { ApiClient } from './base'

export interface Profile {
  name: string
}

export interface ProfileProperty {
  property: string
  value: string
}

export class ProfileApiClient extends ApiClient {
  getProfiles(): Promise<Profile[]> {
    return super.getJson('/profiles')
  }

  getProfile(name: string): Promise<Profile> {
    return super.getJson('/profiles/' + name)
  }

  createProfile(name: string): Promise<Profile> {
    return super.postJson('/profiles', { name })
  }

  deleteProfile(name: string): Promise<void> {
    return super.delete(`/profiles/${name}`)
  }

  getProperties(profileName: string): Promise<ProfileProperty[]> {
    return super.getJson(`/profiles/${profileName}/properties`)
  }

  downloadData(profileName: string): Promise<void> {
    return super.getFile(`/profiles/${profileName}/download`)
  }
}

/**
 * Gets the currently selected profile. Throws an error in any case where
 * the route doesn't contain profile name information.
 * @param route The route to get the profile from.
 * @returns The currently selected profile name, via the current route.
 */
export function getSelectedProfile(route: RouteLocation): string {
  if (!('profileName' in route.params)) {
    throw new Error('No "profileName" route property available.')
  }
  const name = route.params.profileName
  if (Array.isArray(name)) {
    throw new Error('"profileName" route property is an array. Expected a single string.')
  }
  return name
}

const LAST_PROFILE_USED_KEY = 'last-profile-used'

export function saveLastProfileUsed(route: RouteLocation) {
  try {
    const profileName = getSelectedProfile(route)
    const existing = localStorage.getItem(LAST_PROFILE_USED_KEY)
    if (existing === null || existing !== profileName) {
      localStorage.setItem(LAST_PROFILE_USED_KEY, profileName)
    }
  } catch {
    localStorage.removeItem(LAST_PROFILE_USED_KEY)
  }
}

export function getLastProfileUsed(): string | null {
  return localStorage.getItem(LAST_PROFILE_USED_KEY)
}
