import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import {FormBuilder} from '@angular/forms';
import {MatDialogRef} from '@angular/material/dialog';
import {UserCounterLoginService} from '../../../../../core/service/permission/user-counter-login.service';
import {SweetalertService} from "../../../../../core/service/sweetalert/sweetalert";
import {formatDate} from "@angular/common";
import {UserCountersService} from "../../../../../core/service/permission/user-counters.service";
import {tap} from "rxjs/operators";

@Component({
  selector: 'app-user-counter-login',
  templateUrl: './user-counter-login.component.html',
  styleUrls: ['./user-counter-login.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserCounterLoginComponent implements OnInit {
  form;
  constructor(
    private fb: FormBuilder,
    private swSV: SweetalertService,
    private userCounterSV: UserCountersService,
    protected userCouterLoginSV: UserCounterLoginService,
    private dialogRef: MatDialogRef<UserCounterLoginComponent>,
  ) {
    this.form = this.fb.group({
      pin: null,
    });
  }

  ngOnInit(): void {
  }

  login(){
    let datasendBack: any = null;
    console.log(this.form.getRawValue());
    this.userCouterLoginSV.checkpin(this.form.get('pin').value).subscribe(
      result => {
        datasendBack = result;
        console.log(datasendBack)
        if (datasendBack.counter_periods.length === 0){
          console.log(1)
          this.userCounterSV.logout(this.form.get('pin').value).subscribe();
          this.swSV.errText('PIN นี้ไม่อยู่ในช่วงเวลาที่เข้าสู่ระบบได้');
          this.dialogRef.close();
        }else {
          const isdayOk = this.checkDate(datasendBack.counter_open_date, datasendBack.counter_close_date);
          console.log(datasendBack.counter_periods[0]);
          if (isdayOk === false){
            this.userCounterSV.logout(this.form.get('pin').value).subscribe();
            return this.swSV.errText('PIN นี้ไม่อยู่ในช่วงวันที่เข้าสู่ระบบได้');
          }else {
            if (datasendBack.counter_periods[0] === null){
              this.userCounterSV.logout(this.form.get('pin').value).subscribe();
              return this.swSV.errText('PIN นี้ไม่อยู่ในช่วงเวลาที่เข้าสู่ระบบได้');
            }else {
              const isTimeOk = this.checkTime(datasendBack.counter_periods[0].counter_open_time, datasendBack.counter_periods[0].counter_close_time);
              console.log(isTimeOk)
              if (isdayOk && isTimeOk){
                console.log(2)
                this.dialogRef.close(datasendBack);
              }else {
                console.log(3)
                this.userCounterSV.logout(this.form.get('pin').value).subscribe();
                this.swSV.errText('PIN นี้ไม่อยู่ในช่วงเวลาที่เข้าสู่ระบบได้');
                this.dialogRef.close();
              }
            }
          }
        }
      },
      error => {
        this.swSV.errTextAndDetail('เกิดข้อผิดพลาด', 'PIN นี้ไม่มีอยู่ในระบบหรือมีการใช้งานอยู่');
        this.dialogRef.close();
      }
    );
  }

  checkDate(dateOpen, dateClose){
    console.log(dateOpen)
    console.log(dateClose)
    const dateDate = new Date();


    // const dateFrom: any = formatDate(dateOpen, 'mm/dd/yyyy', 'en-US');
    const dateFrom2: any = formatDate(dateOpen, 'MM-dd-yyyy', 'en-US');

    // const dateTo: any = formatDate(dateClose, 'mm/dd/yyyy', 'en-US');
    const dateTo2: any = formatDate(dateClose, 'MM-dd-yyyy', 'en-US');


    // const dateCheck: any = formatDate(dateDate, 'mm/dd/yyyy', 'en-US');
    // const dateCheck2: any = formatDate(dateDate, 'yyyy-MM-dd', 'en-US');
    const dateCheck2: any = formatDate(dateDate, 'MM-dd-yyyy', 'en-US');


    // const d1 = dateFrom.split("/");
    // const d2 = dateTo.split("/");
    // const c = dateCheck.split("/");
    const d1 = dateFrom2.split('-');
    const d2 = dateTo2.split('-');
    const c = dateCheck2.split('-');
    console.log(d1)
    console.log(d2)
    console.log(c)
    // const froms = new Date(d1[2], parseInt(d1[1])-1, d1[0]);  // -1 because months are from 0 to 11
    // const to   = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
    // const check = new Date(c[2], parseInt(c[1])-1, c[0]);
    const froms = d1[2]+d1[0]+d1[1];
    const to = d2[2]+d2[0]+d2[1];
    const check = c[2]+c[0]+c[1];
    // console.log(+froms,'from');
    // console.log(+to,'to');
    // console.log(+check,'check');
    // console.log(+check > +froms && +check < +to);

    return check >= froms && check < to;
  }

  checkTime(start, end){
    const dateCheck2: any = formatDate(new Date(), 'HH:mm:ss', 'en-US');
    // console.log(Date.parse(`01/01/2011 ${dateCheck2}`),'check')
    // console.log(Date.parse(`01/01/2011 ${start}`),'from')
    // console.log(Date.parse(`01/01/2011 ${end}`),'to')
    const from = Date.parse(`01/01/2011 ${start}`)
    const to   =  Date.parse(`01/01/2011 ${end}`)
    const check =  Date.parse(`01/01/2011 ${dateCheck2}`)
    return check > from && check < to;

  }

  cancel(){
    this.dialogRef.close();
  }

}
