import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment';
import { MessageService } from 'primeng/api';
import { ValidationService } from 'src/app/core/common/validation.service';
import { ActivitySlot } from 'src/app/core/models/Experience-Service/slot/add-slots-model';
// import { ActivitySlot } from 'src/app/core/models/Experience-Service/slot/add-slots.model';
import { API } from 'src/app/core/services/api.service';
import { CommonService } from 'src/app/core/services/common.service';

@Component({
  selector: 'app-add-slots',
  templateUrl: './add-slots.component.html',
})
export class AddSlotsComponent implements OnInit {
  date8: Date;
  timeZoneData: any;
  slot_id: any;
  constructor(
    public fb: FormBuilder,
    public ApiServ: API,
    public router: Router,
    public validationService: ValidationService,
    public MsgService: MessageService,
    public routes: ActivatedRoute
  ) { }
  SaveAddSlot: FormGroup;
  date1 = new Date();
  date2 = new Date();
  ngOnInit(): void {
    this.initform();
    this.GetData();
    this.GetSlotId();
    this.date1.setHours(0);
    this.date1.setMinutes(0);
    this.date1.setSeconds(0);
    this.date2.setHours(0);
    this.date2.setMinutes(0);
    this.date2.setSeconds(0);
  }

  initform() {
    this.SaveAddSlot = this.fb.group({
      start_time: [this.date1, Validators.required],
      start_time_Check: [false],
      end_time_Check: [false],
      end_time: [this.date2, Validators.required],
      cut_off_time: [this.date2, Validators.required],
      timezone: this.validationService.required,
    });
  }

  GetData() {
    this.ApiServ.Get('/TimezoneCity/GetAllTimezoneCity').subscribe((res) => {
      if (res) {
        this.timeZoneData = res;
      }
    });
  }
  //this function is user for edit
  GetSlotId() {
    this.routes.queryParams.subscribe((d) => {
      if (d['id']) {
        this.slot_id = d['id'];
        this.ApiServ.Get('/ActivitySlot/GetSlot/' + d['id']).subscribe(
          (data) => {
            if (data) {
              this.AllSetvalue(data['responseObject']);
            }
          }
        );
      }
    });
  }

  AllSetvalue(val) {
    Object.keys(val).forEach((li) => {
      if (li == 'cut_off_time' || li == 'start_time' || li == 'end_time') {
        let date = val[li].split('T');
        let st = moment().utc().format('MM-DD-YYYY ' + date[1]);
        let date1 = new Date(st);
        this.SaveAddSlot.get(li).setValue(date1);
      }
      if (li == 'timezone') {
        this.SaveAddSlot.get(li).setValue(val[li]);
      }
    });
  }

  Save() {

    if (this.SaveAddSlot.status == 'INVALID') {
      console.log(this.SaveAddSlot.get('start_time'));
      this.validationService.showValidationsMsg(this.SaveAddSlot);
      console.log(this.SaveAddSlot);
      return;
    }
    let val = this.SaveAddSlot.getRawValue();
    var now = new Date(val.start_time);
    var d = new Date(val.end_time);
    if (now.getTime() == d.getTime() || now.getTime() >= d.getTime()) {
      this.SaveAddSlot.get('start_time_Check').setValue(true);
      this.SaveAddSlot.get('end_time_Check').setValue(true);
      return
    }
    let postdata = new ActivitySlot();
    postdata.activity_id = CommonService.getSessionStoage('activity_id');
    postdata.start_time =
      '0001-01-01' + 'T' + moment(val.start_time).format('HH:mm:01');
    postdata.end_time =
      '0001-01-01' + 'T' + moment(val.end_time).format('HH:mm:01');
    postdata.cut_off_time =
      '0001-01-01' + 'T' + moment(val.cut_off_time).format('HH:mm:01');
    postdata.timezone = val.timezone;
    postdata.is_deleted = false;
    postdata.activity_slot_id = this.slot_id ? this.slot_id : '';
    postdata.org_id = '';
    postdata.supplier_id = '';

    if (this.slot_id) {
      this.ApiServ.Post('/ActivitySlot/UpdateActivitySlot', postdata).subscribe(
        (res) => {
          if (res) {
            console.log(res);
            this.MsgService.add({
              severity: res['status'] ? 'success' : 'error',
              detail: res['message'],
            });
            setTimeout(() => {
              this.router.navigate([
                '/Services/ActivityServices/ExpServices/Manage',
              ]);
            }, 500);
          }
        }
      );
    } else {
      this.ApiServ.Post('/ActivitySlot/SaveActivitySlot', postdata).subscribe(
        (res) => {
          if (res) {
            console.log(res);
            this.MsgService.add({
              severity: res['status'] ? 'success' : 'error',
              detail: res['message'],
            });
            setTimeout(() => {
              this.router.navigate([
                '/Services/ActivityServices/ExpServices/Manage',
              ]);
            }, 500);
          }
        }
      );
    }
  }



  //
  Check() {
    let val = this.SaveAddSlot.getRawValue();
    var now = new Date(val.start_time);
    var d = new Date(val.end_time);
    if (now.getTime() == d.getTime() || now.getTime() >= d.getTime()) {
      this.SaveAddSlot.get('start_time_Check').setValue(true);
      this.SaveAddSlot.get('end_time_Check').setValue(true);
    } else {
      this.SaveAddSlot.get('start_time_Check').setValue(false);
      this.SaveAddSlot.get('end_time_Check').setValue(false);
    }
  }
}
