import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment';
import { MessageService } from 'primeng/api';
import { API } from 'src/app/core/services/api.service';
import { CommonService } from 'src/app/core/services/common.service';
import { ValidationService } from 'src/app/core/common/validation.service';
import { ActivitySeason, ActivitySeasonDetails } from 'src/app/core/models/Experience-Service/season-setting/season-setting-add.model';
@Component({
  selector: 'app-add-new-season',
  templateUrl: './add-new-season.component.html',
})
export class AddNewSeasonComponent implements OnInit {
  CommonCalender!: string;
  minDateLst = []
  AddSeasonForm;
  season_id;
  messageService: any;
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private ApiServ: API,
    private MsgService: MessageService,
    public validationService: ValidationService,
    private fb: FormBuilder
  ) { }

  ngOnInit(): void {
    this.initForm();
    this.minDateLst.push(new Date())
    this.update()
  }
  update() {
    this.route.queryParams.subscribe(obj => {
      if (obj['id']) {
        this.ApiServ.Get('/ActivitySeason/GetActivitySeason/' + obj['id']).subscribe(d => {
          this.SetValue(d['responseObject']);
          this.season_id = obj['id'];
        });
      }
    });
  }

  initForm() {
    this.AddSeasonForm = this.fb.group({
      season_name: this.validationService.required,
      // supplier_id: ['2205221841391724322'],
      activity_id: CommonService.getSessionStoage('activity_id'),
      org_id: ['2105311837100000021'],
      Calender: this.fb.array([
        this.fb.group({
          CalenderDate: [[new Date(), new Date()]]
        })
      ])
    })
  }
  SetValue(value) {
    this.AddSeasonForm.get("season_name").setValue(value[0].activitySeason.season_name)
    this.Calenders.clear()
    for (let i = 0; i < value[0].seasondateRange.length; i++) {
      this.Calenders.push(this.fb.group({
        CalenderDate: [[,]]
      }))
      let first = new Date(value[0].seasondateRange[i].fromDate);
      let last = new Date(value[0].seasondateRange[i].toDate);

      this.Calenders.controls[i].get('CalenderDate').setValue([first, last]);
      this.minDateLst[i] = first
    }
  }
  get Calenders() {
    return this.AddSeasonForm.get('Calender') as FormArray;
  }

  onSelect(elem, index) {
    for (let i = index + 1; i < this.Calenders.controls.length; i++) {
      let value = this.Calenders.controls[index].value
      this.Calenders.controls[i].get('CalenderDate').setValue([
        new Date(moment(value.CalenderDate[1]).add(1, 'days').format()),//start date
        new Date(moment(value.CalenderDate[1]).add(1, 'days').format()) //end date
      ]);
      this.minDateLst[i] = new Date(moment(value.CalenderDate[1]).add(1, 'days').format())
    }

  }
  addSeasonSetting(checkDate) {
    if (checkDate) {
      let value = this.Calenders.controls[this.Calenders.controls.length - 1].value
      this.Calenders.push(this.fb.group({
        CalenderDate: [[
          new Date(moment(value.CalenderDate[1]).add(1, 'days').format()),//start date
          new Date(moment(value.CalenderDate[1]).add(1, 'days').format())//end date
        ]]
      }));
      this.minDateLst.push(new Date(moment(value.CalenderDate[1]).add(1, 'days').format()))
    };
  }

  SaveSeason() {
    if (this.AddSeasonForm.status == "INVALID") {
      this.validationService.showValidationsMsg(this.AddSeasonForm);
      return;
    }
    let dateArray = []
    for (let i = 0; i < this.Calenders.controls.length; i++) {

      let value = this.Calenders.controls[i].value
      let newdate = value.CalenderDate
      dateArray.push({
        FromDate: moment(newdate[0]).format('YYYY-MM-DD'),
        ToDate: moment(newdate[1]).format('YYYY-MM-DD')
      })
    }
    let value = this.AddSeasonForm.getRawValue()
    let SeasonModel = new ActivitySeasonDetails()
    let Season = new ActivitySeason()
    Season.org_id = '';
    Season.season_name = value.season_name;
    Season.activity_id = value.activity_id;
    Season.supplier_id = ''
    Season.activity_season_id = this.season_id ? this.season_id : '';

    SeasonModel.activitySeason = Season;
    Season.created_by = '';
    Season.updated_by = ''
    SeasonModel.seasondateRange = dateArray;

    if (this.season_id) {
      this.ApiServ.Post('/ActivitySeason/UpdateActivitySeason', SeasonModel).subscribe(data => {
        if (data) {
          this.MsgService.add({
            severity: data['status'] ? 'success' : 'error',
            detail: data['message'],
          });
          setTimeout(() => {
            data['status'] ? this.btnClick() : ''
          }, 500);
        }
      });
    } else {
      this.ApiServ.Post('/ActivitySeason/SaveActivitySeason', SeasonModel).subscribe(data => {
        if (data) {
          this.MsgService.add({
            severity: data['status'] ? 'success' : 'error',
            detail: data['message'],
          });
          setTimeout(() => {
            data['status'] ? this.btnClick() : ''
          }, 500);
        }
      });
    }
  };
  removeSeasonSetting(index: number) {
    this.Calenders.removeAt(index)
    this.minDateLst.splice(index, 1)
  }
  btnClick() {
    this.router.navigateByUrl("/Services/ActivityServices/ExpServices/Manage");
  }
  descreption: string = '';

  showInfo(descreption) {
    this.descreption = descreption;
    this.messageService.add({ severity: 'info', summary: 'samary', detail: '' });
  }
}
