import { Component, OnInit, ViewChild } from '@angular/core';

import { FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';

import { AuthService } from './../../services/auth.service';
import { ItemService } from './../../services/item.service';
import { I18nService } from './../../services/i18n.service';
import { PermissionService } from './../../services/permission.service';
import { QuotaService } from './../../services/quota.service';

@Component({
  selector: 'app-tokens',
  templateUrl: './tokens.component.html',
  styleUrls: ['./tokens.component.scss']
})
export class TokensComponent implements OnInit {

  form: FormGroup;
  @ViewChild('formDirective') private formDirective: NgForm;
  public tokenInvalid: boolean;
  public tokenRedeemed: boolean;
  auth;
  items = [];
  permissions = [];
  quotas = [];
  currentLocale: String;

  constructor(private formBuilder: FormBuilder,
    private authService: AuthService,
    private itemService: ItemService,
    private i18n: I18nService,
    private permissionService: PermissionService,
    private quotaService: QuotaService,
    private router: Router,
    private route: ActivatedRoute) {

    this.currentLocale = this.i18n.getLocale();

    this.authService.auth.subscribe(data => {
      this.auth = data;
    })

    this.update();
  }

  async ngOnInit() {
    this.form = this.formBuilder.group({
      token: ['', Validators.required]
    });

    this.route.queryParams.subscribe(params => {
      if (params.token) {
        this.itemService.redeemSecret(params.token).subscribe((data: any) => {
          this.update();
          this.router.navigate(
            ['.'],
            { relativeTo: this.route }
          );
        }, error => {
          this.form.get('token').patchValue(params.token);
          if (error.status == 410) {
            this.tokenRedeemed = true;
          } else {
            this.tokenInvalid = true;
          }
        })
      }
    });
  }

  redeemSecret() {
    this.tokenInvalid = false;
    this.tokenRedeemed = false;
    if (this.form.valid) {
      const secret = this.form.get('token').value;
      this.itemService.redeemSecret(secret).subscribe((data: any) => {
        this.formDirective.resetForm();
        this.update();
      }, error => {
        if (error.status == 410) {
          this.tokenRedeemed = true;
        } else {
          this.tokenInvalid = true;
        }
      })
    }
  }

  removeSecret(secret: String) {
    this.itemService.removeSecret(secret).subscribe((data: any) => {
      this.update();
    }, error => {
    })
  }

  redeem() {
    if (this.auth.authenticated) {
      this.itemService.redeem().subscribe((data: any) => {
        this.router.navigate(["/account/info"]);
      })
    }
  }

  update() {
    this.authService.getAuth().then(response => {
      this.itemService.items().subscribe((data: any) => {
        this.items = data;
      });

      this.permissionService.permissionsNew().subscribe((data: any) => {
        this.permissions = data;
      })

      this.quotaService.quotasNew().subscribe((data: any) => {
        this.quotas = data;
      })
    }).catch(function (error) { });;
  }

  canRegister() {
    return this.permissions && this.permissions.some(function (permission) {
      return !permission.addon;
    })
  }

}
