// noinspection CssUnresolvedCustomProperty
import { App, Plugin, PluginSettingTab, Setting } from 'obsidian'
import { RecencyCutoff } from '../globals'
import type LocatorPlugin from '../main'
import { enableVerboseLogging } from '../tools/utils'
import { injectSettingsBehavior } from './settings-behavior'
import { injectSettingsDanger } from './settings-danger'
import { injectSettingsHttp } from './settings-http'
import { injectSettingsIndexing } from './settings-indexing'
import { injectSettingsUserInterface } from './settings-ui'
import { injectSettingsWeighting } from './settings-weighting'
import { type LocatorSettings, saveSettings, showExcerpt } from './utils'

export class SettingsTab extends PluginSettingTab {
  plugin: LocatorPlugin

  constructor(plugin: LocatorPlugin) {
    super(plugin.app, plugin)
    this.plugin = plugin

    showExcerpt.subscribe(async v => {
      settings.showExcerpt = v
      await saveSettings(this.plugin)
    })
  }

  display(): void {
    const { containerEl } = this

    containerEl.empty()

    // Settings main title
    containerEl.createEl('h1', { text: 'Locator' })

    // Sponsor link - Thank you!
    const divSponsor = containerEl.createDiv()
    divSponsor.innerHTML = `
        <iframe sandbox="allow-top-navigation-by-user-activation" src="https://github.com/sponsors/scambier/button" title="Sponsor scambier" height="35" width="116" style="border: 0;"></iframe>
        <a href='https://ko-fi.com/B0B6LQ2C' target='_blank'><img height='36' style='border:0px;height:36px;' src='https://cdn.ko-fi.com/cdn/kofi2.png?v=3' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a> 
    `

    injectSettingsIndexing(this.plugin, settings, containerEl)
    containerEl.createEl('hr')
    injectSettingsBehavior(this.plugin, settings, containerEl)
    containerEl.createEl('hr')
    injectSettingsUserInterface(this.plugin, settings, containerEl)
    containerEl.createEl('hr')
    injectSettingsWeighting(this.plugin, settings, containerEl, this.display)
    containerEl.createEl('hr')
    injectSettingsHttp(this.plugin, settings, containerEl)
    containerEl.createEl('hr')
    injectSettingsDanger(this.plugin, settings, containerEl)
    containerEl.createEl('hr')

    //#region Debugging

    new Setting(containerEl).setName('Debugging').setHeading()

    new Setting(containerEl)
      .setName('Enable verbose logging')
      .setDesc(
        'Adds a LOT of logs for debugging purposes. You also need to enable "Verbose" logging in the console to see these logs.'
      )
      .addToggle(toggle =>
        toggle.setValue(settings.verboseLogging).onChange(async v => {
          settings.verboseLogging = v
          enableVerboseLogging(v)
          await saveSettings(this.plugin)
        })
      )

    //#endregion Debugging

    //#region Danger Zone

    //#endregion Danger Zone
  }
}

export function getDefaultSettings(app: App): LocatorSettings {
  return {
    useCache: true,
    hideExcluded: false,
    recencyBoost: RecencyCutoff.Disabled,
    downrankedFoldersFilters: [] as string[],
    indexedFileTypes: [] as string[],
    displayTitle: '',
    PDFIndexing: false,
    officeIndexing: false,
    imagesIndexing: false,
    unsupportedFilesIndexing: 'default',
    openInNewPane: false,
    vimLikeNavigationShortcut: app.vault.getConfig('vimMode') as boolean,

    ribbonIcon: true,
    showExcerpt: true,
    maxEmbeds: 5,
    renderLineReturnInExcerpts: true,
    showCreateButton: false,
    simpleSearch: false,
    fuzziness: '1',

    weightBasename: 10,
    weightDirectory: 7,
    weightH1: 6,
    weightH2: 5,
    weightH3: 4,
    weightUnmarkedTags: 2,
    weightCustomProperties: [] as { name: string; weight: number }[],

    httpApiEnabled: false,
    httpApiPort: '51361',

    welcomeMessage: '',
    verboseLogging: false,

    DANGER_httpHost: null,
  }
}

export let settings: LocatorSettings

// /**
//  * @deprecated
//  */
// export function getSettings(): LocatorSettings {
//   if (!settings) {
//     settings = Object.assign({}, getDefaultSettings()) as LocatorSettings
//   }
//   return settings
// }

export async function loadSettings(plugin: Plugin): Promise<LocatorSettings> {
  settings = Object.assign(
    {},
    getDefaultSettings(plugin.app),
    await plugin.loadData()
  )
  showExcerpt.set(settings.showExcerpt)
  enableVerboseLogging(settings.verboseLogging)
  return settings
}
