<template>
  <div class="absolute right-5 top-[max(0.75rem,env(safe-area-inset-top))]">
    <span class="align-center text-red-500 mr-2">{{ message }}</span>
    <span class="ml-2">
      <router-link
        :to="{ name: 'help' }"
        class="text-xs uppercase bg-gradient-to-b from-blue-400 to-blue-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-1.5 py-1 rounded-md ml-1"
      >
        Help
      </router-link>
    </span>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop } from "vue-facing-decorator";

import { AppString, NotificationIface } from "../constants/app";
import { MASTER_SETTINGS_KEY } from "../db/tables/settings";
import { DEFAULT_ENDORSER_API_SERVER } from "../constants/app";
import {
  PlatformServiceMixin,
  IPlatformServiceMixin,
} from "../utils/PlatformServiceMixin";
import { mapColumnsToValues, parseJsonField } from "../db/databaseUtil";

@Component({
  mixins: [PlatformServiceMixin],
})
export default class TopMessage extends Vue {
  // NOTE: This component uses PlatformServiceMixin which provides:
  // - this.dbQuery(), this.dbExec(), this.dbGetOneRow() methods
  // - this.platformService computed property
  // - this.isCapacitor, this.isWeb, this.isElectron computed properties
  // - this.capabilities computed property
  // TypeScript requires (this as any) for mixin methods due to compile-time limitations

  $notify!: (notification: NotificationIface, timeout?: number) => void;

  @Prop selected = "";

  message = "";

  async mounted() {
    try {
      const settings = await this.getActiveAccountSettings();
      if (
        settings.warnIfTestServer &&
        settings.apiServer !== AppString.PROD_ENDORSER_API_SERVER
      ) {
        const didPrefix = settings.activeDid?.slice(11, 15);
        this.message = "You're not using prod, user " + didPrefix;
      } else if (
        settings.warnIfProdServer &&
        settings.apiServer === AppString.PROD_ENDORSER_API_SERVER
      ) {
        const didPrefix = settings.activeDid?.slice(11, 15);
        this.message = "You are using prod, user " + didPrefix;
      }
    } catch (err: unknown) {
      this.$notify(
        {
          group: "alert",
          type: "danger",
          title: "Error Detecting Server",
          text: JSON.stringify(err),
        },
        -1,
      );
    }
  }

  /**
   * Get settings for the active account using the platform service mixin.
   * This demonstrates the concise mixin pattern with direct database access.
   */
  private async getActiveAccountSettings() {
    // Declare defaultSettings outside try block for proper scope
    let defaultSettings;

    try {
      // Get default settings first
      defaultSettings = await this.getDefaultSettings();

      // If no active DID, return defaults
      if (!defaultSettings.activeDid) {
        return defaultSettings;
      }

      // Get account-specific settings using the mixin (much more concise!)
      const result = await (this as any).dbQuery(
        "SELECT * FROM settings WHERE accountDid = ?",
        [defaultSettings.activeDid],
      );

      if (!result?.values?.length) {
        return defaultSettings;
      }

      // Map and filter settings
      const overrideSettings = mapColumnsToValues(
        result.columns,
        result.values,
      )[0] as any;

      const overrideSettingsFiltered = Object.fromEntries(
        Object.entries(overrideSettings).filter(([_, v]) => v !== null),
      );

      // Merge settings
      const settings = { ...defaultSettings, ...overrideSettingsFiltered };

      // Handle searchBoxes parsing
      if (settings.searchBoxes) {
        settings.searchBoxes = parseJsonField(settings.searchBoxes, []);
      }

      return settings;
    } catch (error) {
      console.error(
        `Failed to retrieve account settings for ${defaultSettings?.activeDid}:`,
        error,
      );
      return (
        defaultSettings || {
          id: MASTER_SETTINGS_KEY,
          activeDid: undefined,
          apiServer: DEFAULT_ENDORSER_API_SERVER,
        }
      );
    }
  }

  /**
   * Get default settings using the platform service mixin
   */
  private async getDefaultSettings() {
    try {
      // Direct database access via mixin - no destructuring needed!
      const result = await (this as any).dbQuery("SELECT * FROM settings WHERE id = ?", [
        MASTER_SETTINGS_KEY,
      ]);

      if (!result?.values?.length) {
        return {
          id: MASTER_SETTINGS_KEY,
          activeDid: undefined,
          apiServer: DEFAULT_ENDORSER_API_SERVER,
        };
      }

      const settings = mapColumnsToValues(
        result.columns,
        result.values,
      )[0] as any;

      // Handle searchBoxes parsing
      if (settings.searchBoxes) {
        settings.searchBoxes = parseJsonField(settings.searchBoxes, []);
      }

      return settings;
    } catch (error) {
      console.error("Failed to retrieve default settings:", error);
      return {
        id: MASTER_SETTINGS_KEY,
        activeDid: undefined,
        apiServer: DEFAULT_ENDORSER_API_SERVER,
      };
    }
  }
}
</script>
