import { Component, Prop, Vue } from 'vue-property-decorator';
import { v4 } from 'uuid';
import get from 'lodash/get';
import isFunction from 'lodash/isFunction';
import { Tab } from '@interfaces/base/BaseTabs';
@Component({})
export default class BaseTabs extends Vue {
  @Prop({
    required: true,
  })
  private currentTab!: Tab;

  @Prop({
    default: () => [],
  })
  private tabs?: Tab[];

  @Prop({
    default: true,
  })
  private clickHandler?: boolean | ((tab: Tab) => void) | undefined;

  private get tabsCast(): Tab[] {
    return (
      this.tabs?.map((tab: Tab) => {
        const result: Tab = {
          ...tab,
        };

        if (!result.id) {
          result.id = v4();
        }

        return result;
      }) || []
    );
  }

  private clickHandlerCast(tab: Tab): void {
    this.$emit('click', tab);

    if (this.clickHandler) {
      if (typeof this.clickHandler === 'function') {
        this.clickHandler(tab);
      } else {
        const query = this.$route.query;
        delete query.lock;
        this.$router.replace({
          name: 'cards',
          params: {
            id: this.$route.params.id,
            path: this.$route.params.path,
          },
          query: {
            ...query,
            active: tab.path,
          },
        });
      }
    }
  }

  private isVisible(tab: Tab): boolean {
    let result = get(tab, 'visible');

    if (isFunction(result)) {
      result = result(tab);
    }

    return !!result;
  }
}
