<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Hello Plunker!</h1>
  </body>

</html>
// Code goes here

/* Styles go here */

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { FormGroup, FormControl, Validators, FormArray, FormBuilder } from '@angular/forms';


import { Subscription } from 'rxjs/rx';
import { HttpService } from '../../services/http.service';

import * as sharedMethods from '../../shared-methods';

@Component({
  selector: 'app-sale-person-info',
  templateUrl: './sale-person-info.component.html',
  styles: []
})
export class SalePersonInfoComponent implements OnInit, OnDestroy {

  personForm: FormGroup;
  formSubmitted = false;
  checkedForm = false;
  formItemsArray: any;

  private routeSubscription: Subscription;
  eventsArray;
  data;
  redTimer;


  constructor(
    private httpService: HttpService,
    private activatedRoute: ActivatedRoute,
    private formBuilder: FormBuilder
  ) {
    this.routeSubscription = this.activatedRoute.queryParams.subscribe(
      queryParam => {
        if (queryParam['eventId']) {
          this.getEvent(queryParam['eventId']);
        }
      }
    );
  }

  createForm() {

    this.personForm = this.formBuilder.group({
      formItemsArray: this.formBuilder.array([this.createItem()])
    });

  }
  createItem(): FormGroup {
    return this.formBuilder.group({
      'tcNo': new FormControl('', [Validators.required, sharedMethods.checkTcNo]),
      'passportNo': new FormControl(''),
      'notTcCitizen': new FormControl(''),
      'cepNo': new FormControl(''),
      'ticketId': new FormControl('')
    });
  }

  createItem2(): FormGroup {
    return this.formBuilder.group({
      'tcNo': new FormControl('1'),
      'passportNo': new FormControl('1', [Validators.required]),
      'notTcCitizen': new FormControl(''),
      'cepNo': new FormControl('1', [Validators.required]),
      'ticketId': new FormControl('')
    });
  }

  addItem(): void {
    this.formItemsArray = this.personForm.get('formItemsArray') as FormArray;
    this.formItemsArray.push(this.createItem());
  }

  checkIfNotTcCitizen(e, index?) {
    let otherNationsForm = e.target.closest('form').querySelector('.js-other-nations-form');
    let form;

    if (index) {
      form = this.personForm;
    } else {
      form = this.formItemsArray.get(index.toString());
    }

    if (e.target.checked) {
      otherNationsForm.classList.add('opened');

      form.get('tcNo').disable();

      this.formItemsArray = this.personForm.get('formItemsArray') as FormArray;
      this.formItemsArray.setControl(2, this.createItem2());

      // form.setControl('0', this.formBuilder.array([this.createItem2()]));
      // form.setControl('tcNo', new FormControl('222'));
      // form.setControl('passportNo', new FormControl('123', Validators.required));
      // form.setControl('cepNo', new FormControl('123', Validators.required));
    } else {
      otherNationsForm.classList.remove('opened');
      form.get('tcNo').enable();
      form.setControl('tcNo', new FormControl('qqq', [Validators.required, sharedMethods.checkTcNo]));
      form.setControl('passportNo', new FormControl(''));
      form.setControl('cepNo', new FormControl(''));
    }
  }

  onSubmit() {
    console.log(this.personForm);

    this.checkedForm = true;

    if (!this.personForm.valid) {
      console.log('invalid form');
      return;
    }

    const body = {
      passportNo: this.personForm.value.passportNo,
      email: this.personForm.value.email,
      cepNo: this.personForm.value.cepNo,
      password: this.personForm.value.password,
    };

    if (this.personForm.value.notTcCitizen) {
      body['passportNo'] = this.personForm.value.passportNo;
    } else {
      body['tcNo'] = this.personForm.value.tcNo;
    }

    // this.authService.signupUser(body, 'api/signupuser', this.afterSignup);
  }


  getEvent(paramEventId) {
    const params = {
      eventId: paramEventId
    };

    this.httpService.request(false, 'get', 'api/salePersonInfo', params).subscribe(
      res => {
        if (res.isOk) {
          this.data = res.body.data;
          this.eventsArray = this.data;
          for (const ticket of this.data.tickets) {
            this.addItem();
          }
        } else {
          console.log('get eventDetails error', res);
        }
      },
      err => {
        console.log('get eventDetails error', err);
      }
    );
  }

  ngOnInit() {
    this.startTimer(60 * 5, document.querySelector('.timer'));
    this.createForm();
  }

  ngOnDestroy() {
    if (this.redTimer) {
      this.redTimer.stopTimer();
    }
  }

  // Timer Function
  startTimer(duration, el) {
    if (el) {
      this.redTimer = new sharedMethods.Countdown(duration, el);
      this.redTimer.startTimer();

      this.redTimer.finishEvent.subscribe(
        data => {
          console.log(data, 'time up!');
        }
      );
    }
  }

  removeTicket(ticketId) {
    console.log(ticketId);
  }

}