import { Component, Input, OnInit, SimpleChanges, ViewChild } from '@angular/core';
import { FullCalendarComponent, CalendarOptions } from '@fullcalendar/angular';
import { NgbDate, NgbCalendar, NgbDateParserFormatter, NgbNavChangeEvent, NgbModal, ModalDismissReasons, NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { Equirment } from 'src/app/models/equirment.model';
import { ItemDetail } from 'src/app/models/itemDetail.model';
import { RoomDetailService } from 'src/app/service/room-detail.service';
import { ItemDetailService } from 'src/app/service/item-detail.service';
import { MyRoom } from 'src/app/models/rooms.model';
import { EquirmentService } from 'src/app/service/equirment.service';
import { RoomService } from 'src/app/service/room.service';
import { RoomDetail } from 'src/app/models/RoomDetail.model';
import { SearchEqModel } from 'src/app/models/searcheq.model';
import { SearchRoomModel } from 'src/app/models/searchroom.model';

@Component({
  selector: 'ngbd-modal-content',
  templateUrl: './home-page-calendar.component.html',
})

export class NgbdModalContent {
  @Input() roomSelect: RoomDetail;
  telephone;
  rPic;
  rName;
  sTime;
  eTime;
  sDate;
  eDate;
  allDay;

  modelItemDetail = new ItemDetail();
  modelRoomDetail = new RoomDetail();

  constructor(public activeModal: NgbActiveModal) {
    console.log("name", this.roomSelect)
  }

  ngOnChanges(changes: SimpleChanges) {
    console.log("sssssssssss", this.roomSelect)
  }

}

@Component({
  selector: 'ngbd-modal-content',
  templateUrl: './home-page-lend-calendar.component.html',
})

export class NgbdModalLendContent {
  @Input() itemSelect: ItemDetail; 
  telephone;
  eqPic;
  eqName;
  quantity;
  sDate;

  constructor(public activeModal: NgbActiveModal) {
    console.log("name", this.itemSelect)
  }
}

@Component({
  selector: 'app-home-page',
  templateUrl: './home-page.component.html',
  styleUrls: ['./home-page.component.scss'],
  styles: [`
  .form-group.hidden {
    width: 0;
    margin: 0;
    border: none;
    padding: 0;
  }
  .custom-day {
    text-align: center;
    padding: 0.185rem 0.25rem;
    display: inline-block;
    height: 2rem;
    width: 2rem;
  }
  .custom-day.focused {
    background-color: #e6e6e6;
  }
  .custom-day.range, .custom-day:hover {
    background-color: rgb(2, 117, 216);
    color: white;
  }
  .custom-day.faded {
    background-color: rgba(2, 117, 216, 0.5);
  }
`],
})


export class HomePageComponent implements OnInit {
  active = 1;
  public gfg = true;
  page = 1;
  pageSize = 10;
  @ViewChild('calendarBook') calendarBook: FullCalendarComponent

  listItemDetail: ItemDetail[] = [];
  listRoomDetail: RoomDetail[] = [];

  modelEquirment = new Equirment();
  modelRoom = new MyRoom();
  modelItemDetail = new ItemDetail();
  modelRoomDetail = new RoomDetail();
  selectedRoomDetail = new RoomDetail();
  selectedItemDetail = new ItemDetail();
  searcheqModel : SearchEqModel = new SearchEqModel();
  searchroomModel : SearchRoomModel = new SearchRoomModel();

  hoveredDate: NgbDate | null = null;

  fromDate: NgbDate | null;
  toDate: NgbDate | null;

  showBook = false;
  eventRoom = [];
  eventEquirment = [];

  showModal: boolean;
  title = 'ngularfullcalendarbootstrap';
  name: string;
  date: string;

  closeResult = '';

  calendarRoom: CalendarOptions = {
    initialView: 'dayGridMonth',
    dateClick: this.handleDateClick.bind(this), // bind is important!
    locale: "th",
    events: this.eventRoom
  };

  calendarEquirment: CalendarOptions = {
    initialView: 'dayGridMonth',
    dateClick: this.handleDateClick.bind(this), // bind is important!
    locale: "th",
    events: this.eventEquirment
  };

  handleDateClick(arg) {
    // alert('date click! ' + arg.dateStr)
    this.selectedRoomDetail = arg.event.extendedProps;
    console.log(this.selectedRoomDetail)
    this.eventShow();
  }

  handleLendClick(arg) {
    // alert('date click! ' + arg.dateStr)
    this.selectedItemDetail = arg.event.extendedProps;
    console.log(this.selectedItemDetail)
    this.eventLendShow();
  }

  dateKub() {
    return this.listRoomDetail.length
  }

  toggleWeekends() {
    this.calendarRoom.weekends = !this.calendarRoom.weekends // toggle the boolean!
  }

  constructor(private calendar: NgbCalendar, public formatter: NgbDateParserFormatter, private ItemDetailService: ItemDetailService, private RoomDetailService: RoomDetailService, private equirmentService: EquirmentService, private roomService: RoomService,
    private modalService: NgbModal) {
    this.fromDate = calendar.getToday();
    this.toDate = calendar.getNext(calendar.getToday(), 'd', 10);
  }

  private getDismissReason(reason: any): string {
    if (reason === ModalDismissReasons.ESC) {
      return 'by pressing ESC';
    } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
      return 'by clicking on a backdrop';
    } else {
      return `with: ${reason}`;
    }
  }

  onDateSelection(date: NgbDate) {
    if (!this.fromDate && !this.toDate) {
      this.fromDate = date;
    } else if (this.fromDate && !this.toDate && date && date.after(this.fromDate)) {
      this.toDate = date;
    } else {
      this.toDate = null;
      this.fromDate = date;
    }
  }

  isHovered(date: NgbDate) {
    return this.fromDate && !this.toDate && this.hoveredDate && date.after(this.fromDate) && date.before(this.hoveredDate);
  }

  isInside(date: NgbDate) {
    return this.toDate && date.after(this.fromDate) && date.before(this.toDate);
  }

  isRange(date: NgbDate) {
    return date.equals(this.fromDate) || (this.toDate && date.equals(this.toDate)) || this.isInside(date) || this.isHovered(date);
  }

  validateInput(currentValue: NgbDate | null, input: string): NgbDate | null {
    const parsed = this.formatter.parse(input);
    return parsed && this.calendar.isValid(NgbDate.from(parsed)) ? NgbDate.from(parsed) : currentValue;
  }

  ngOnInit(): void {
    setTimeout(function () {
      window.dispatchEvent(new Event('resize'))
    }, 1)
    this.ItemDetailService.getListItemDetail().subscribe(result => {
      this.listItemDetail = result;
      console.log("2", this.listItemDetail)
      for (let i = 0; i < this.listItemDetail.length; i++) {
        if (this.listItemDetail[i].eStatus == 0) {
          this.eventEquirment.push({
            id: this.listItemDetail[i].id,
            title: this.listItemDetail[i].equirments.eqName + " (" + this.listItemDetail[i].userName + ")",
            start: '2021-12-16T10:30:00',
            end: '2021-12-16T11:30:00',
            extendedProps: this.listItemDetail[i],
            description: this.listItemDetail[i].remark,
            color: 'rgb(250,250,250)',
            textColor: 'white'
          }
          )
        }

      }
      this.calendarEquirment = {
        initialView: 'dayGridMonth',
        themeSystem: 'bootstrap',
        dayMaxEventRows: true,
        locale: "th",
        events: this.eventEquirment,
        eventClick: this.handleLendClick.bind(this),
      };


    });
    this.RoomDetailService.getListRoomDetail().subscribe(result => {
      this.listRoomDetail = result;
      console.log("1", this.listRoomDetail)
      for (let i = 0; i < this.listRoomDetail.length; i++) {
        if (this.listRoomDetail[i].rStatus == 0) {
          this.eventRoom.push({
            id: this.listRoomDetail[i].id,
            title: this.listRoomDetail[i].room.rName + " (" + this.listRoomDetail[i].userName + ")",
            start: '2021-12-16T10:30:00',
            end: '2021-12-16T11:30:00',
            extendedProps: this.listRoomDetail[i],
            description: this.listRoomDetail[i].remark,
            allDay: this.listRoomDetail[i].allDay
          }
          )
        }

      }

      this.calendarRoom = {
        initialView: 'dayGridMonth',
        themeSystem: 'bootstrap',
        dayMaxEventRows: true,
        locale: "th",
        events: this.eventRoom,
        eventClick: this.handleDateClick.bind(this),
      };



    });




  }

  test() {
    alert("sssssssss");
  }

  onNavChange(changeEvent: NgbNavChangeEvent) {
    setTimeout(function () {
      window.dispatchEvent(new Event('resize'))
    }, 250);

  }

  eventShow() {
    const modalRef = this.modalService.open(NgbdModalContent);
    modalRef.componentInstance.roomSelect = this.selectedRoomDetail;
    // modalRef.componentInstance.telephone = this.selectedRoomDetail.rTelephone;
    // modalRef.componentInstance.rName = this.selectedRoomDetail.room.rName;
    // modalRef.componentInstance.sTime = this.selectedRoomDetail.sTime;
    // modalRef.componentInstance.eTime = this.selectedRoomDetail.eTime;
    // modalRef.componentInstance.sDate = this.selectedRoomDetail.sDate;
    // modalRef.componentInstance.eDate = this.selectedRoomDetail.eDate;
    // modalRef.componentInstance.allDay = this.selectedRoomDetail.allDay;
  }

  eventLendShow() {
    const modalRef = this.modalService.open(NgbdModalLendContent);
    modalRef.componentInstance.itemSelect = this.selectedItemDetail;
    // modalRef.componentInstance.name = this.selectedItemDetail.userName;
    // modalRef.componentInstance.telephone = this.selectedItemDetail.eTelephone;
    // modalRef.componentInstance.eqName = this.selectedItemDetail.equirments.eqName;
    // modalRef.componentInstance.quantity = this.selectedItemDetail.quantity;
    // modalRef.componentInstance.sDate = this.selectedRoomDetail.sDate;
  }

  openSearchEq() {
    console.log(this.searcheqModel)

    // this.searchService.getSearchEq();
    // this.modalService.dismissAll();
    // this.ngOnInit();

  }

  openSearchRoom() {
    console.log(this.searchroomModel)
    
    // this.searchService.getSearchRoom();
    // this.modalService.dismissAll();
    // this.ngOnInit();

  }
  
}