import { qs } from '@protocol-launcher/shared'

/**
 * New file payload definition.
 */
type New = {
  /**
   * Storage location.
   *
   * @default 'local'
   */
  location?: 'iCloud' | 'local' | 'external'
  /**
   * Directory path.
   *
   * @default root folder
   */
  path?: string
  /**
   * File name. If not specified, a file name will be generated by Textastic.
   */
  name?: string
  /**
   * External folder identifier. Required when location is 'external'.
   *
   * @example '62E8D362-7DFA-413C-874E-20C1D98B17C0'
   */
  externalUUID?: string
  /**
   * Text to insert into the new file.
   */
  text?: string
  /**
   * Snippet to insert. If both snippet and text are present, only snippet will be used.
   *
   * @link http://manual.macromates.com/en/snippets
   */
  snippet?: string
}

/**
 * Create a new file in the local file system or in iCloud.
 *
 * @param payload New file payload.
 * @returns Textastic new file URL.
 * @example
 * newFile({
 *   name: 'foo.txt',
 *   text: 'bar',
 * })
 * // => 'textastic://x-callback-url/new?name=foo.txt&text=bar'
 * @example
 * newFile({
 *   location: 'iCloud',
 *   name: 'foo.txt',
 *   path: 'test',
 *   snippet: 'foo $0 bar',
 * })
 * // => 'textastic://x-callback-url/new?location=iCloud&name=foo.txt&path=test&snippet=foo%20%240%20bar'
 * @link https://www.textasticapp.com/v10/manual/integration_other_apps/x-callback-url.html#new
 */
export function newFile(payload: New = {}) {
  const { location, path, name, externalUUID, text, snippet } = payload
  const params = qs({
    ...(location ? { location } : {}),
    ...(path ? { path } : {}),
    ...(name ? { name } : {}),
    ...(externalUUID ? { externalUUID } : {}),
    ...(text ? { text } : {}),
    ...(snippet ? { snippet } : {}),
  })

  return `textastic://x-callback-url/new${params}`
}
