import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ToastService } from 'src/app/service/toast.service';
import { FormPageBase } from 'src/app/core/base/form-page-base';
import {
  ShortUrl,
  ShortUrlCreateInput,
  ShortUrlUpdateInput,
} from 'src/app/model/entities/short-url';
import { ShortUrlsDataService } from 'src/app/modules/admin/short-urls/short-urls.data.service';
import { Group } from 'src/app/model/entities/group';
import { Domain } from 'src/app/model/entities/domain';

@Component({
  selector: 'app-short-url-form-page',
  templateUrl: './short-url-form-page.component.html',
  styleUrl: './short-url-form-page.component.scss',
})
export class ShortUrlFormPageComponent extends FormPageBase<
  ShortUrl,
  ShortUrlCreateInput,
  ShortUrlUpdateInput,
  ShortUrlsDataService
> {
  groups: Group[] = [];
  domains: Domain[] = [];

  constructor(private toast: ToastService) {
    super();
    this.dataService.getAllAvailableGroups().subscribe(groups => {
      this.groups = groups;
    });
    this.dataService.getAllDomains().subscribe(domains => {
      this.domains = domains;
    });

    if (!this.nodeId) {
      this.node = this.new();
      this.setForm(this.node);

      return;
    }

    this.dataService.loadById(this.nodeId).subscribe(node => {
      this.node = node;
      this.setForm(this.node);
    });
  }

  new(): ShortUrl {
    return {} as ShortUrl;
  }

  buildForm() {
    this.form = new FormGroup({
      id: new FormControl<number | undefined>(undefined),
      shortUrl: new FormControl<string | undefined>(
        undefined,
        Validators.required
      ),
      targetUrl: new FormControl<string | undefined>(
        undefined,
        Validators.required
      ),
      description: new FormControl<string | undefined>(undefined),
      loadingScreen: new FormControl<boolean | undefined>(undefined),
      groupId: new FormControl<number | undefined>(undefined),
      domainId: new FormControl<number | undefined>(undefined),
    });
    this.form.controls['id'].disable();
  }

  private generateRandomString(length: number): string {
    const characters =
      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    const charactersLength = characters.length;
    for (let i = 0; i < length; i++) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
  }

  setForm(node?: ShortUrl) {
    this.form.controls['id'].setValue(node?.id);
    this.form.controls['shortUrl'].setValue(
      node?.shortUrl ?? this.generateRandomString(8)
    );
    this.form.controls['targetUrl'].setValue(node?.targetUrl);
    this.form.controls['description'].setValue(node?.description);
    this.form.controls['loadingScreen'].setValue(node?.loadingScreen);
    this.form.controls['groupId'].setValue(node?.group?.id);
    this.form.controls['domainId'].setValue(node?.domain?.id);
  }

  getCreateInput(): ShortUrlCreateInput {
    return {
      shortUrl: this.form.controls['shortUrl'].value ?? undefined,
      targetUrl: this.form.controls['targetUrl'].pristine
        ? undefined
        : (this.form.controls['targetUrl'].value ?? undefined),
      description: this.form.controls['description'].pristine
        ? undefined
        : (this.form.controls['description'].value ?? undefined),
      loadingScreen: this.form.controls['loadingScreen'].pristine
        ? undefined
        : (this.form.controls['loadingScreen'].value ?? undefined),
      groupId: this.form.controls['groupId'].pristine
        ? undefined
        : (this.form.controls['groupId'].value ?? undefined),
      domainId: this.form.controls['domainId'].pristine
        ? undefined
        : (this.form.controls['domainId'].value ?? undefined),
    };
  }

  getUpdateInput(): ShortUrlUpdateInput {
    if (!this.node?.id) {
      throw new Error('Node id is missing');
    }

    return {
      id: this.form.controls['id'].value,
      shortUrl: this.form.controls['shortUrl'].pristine
        ? undefined
        : (this.form.controls['shortUrl'].value ?? undefined),
      targetUrl: this.form.controls['targetUrl'].pristine
        ? undefined
        : (this.form.controls['targetUrl'].value ?? undefined),
      description: this.form.controls['description'].pristine
        ? undefined
        : (this.form.controls['description'].value ?? undefined),
      loadingScreen: this.form.controls['loadingScreen'].pristine
        ? undefined
        : (this.form.controls['loadingScreen'].value ?? undefined),
      groupId: this.form.controls['groupId'].pristine
        ? undefined
        : (this.form.controls['groupId'].value ?? undefined),
      domainId: this.form.controls['domainId'].pristine
        ? undefined
        : (this.form.controls['domainId'].value ?? undefined),
    };
  }

  create(apiKey: ShortUrlCreateInput): void {
    this.dataService.create(apiKey).subscribe(() => {
      this.spinner.hide();
      this.toast.success('action.created');
      this.close();
    });
  }

  update(apiKey: ShortUrlUpdateInput): void {
    this.dataService.update(apiKey).subscribe(() => {
      this.spinner.hide();
      this.toast.success('action.created');
      this.close();
    });
  }
}
