import { Component, OnInit } from '@angular/core';
import { ServicesService } from 'src/app/services.service';
import { LoginflowService } from '../../data/loginflow.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router, ActivatedRoute, RouterStateSnapshot } from '@angular/router';
import { AuthserviceService } from '../../authservice.service';
import { NgxSpinnerService } from 'ngx-spinner';
import { MatDatepickerInputEvent } from '@angular/material/datepicker';
import { ScheduleserviceService } from 'src/app/services/Schedule/scheduleservice.service';

@Component({
  selector: 'app-studentprofile',
  templateUrl: './studentprofile.component.html',
  styleUrls: ['./studentprofile.component.scss'],
})
export class StudentprofileComponent implements OnInit {
  disableBtn: boolean = true;
  ProfileSetting: boolean = true;
  UserSetting: boolean = false;
  ChangePassword: boolean = false;
  Twofasetting: boolean = false;
  Myenrollments: boolean = false;
  public data: any;
  showMenu: boolean = true;
  name: any;
  imgurl: any;
  FirstName: any;
  Nickname: any;
  Email: any;
  UpdateForm: FormGroup;
  submitted = false;
  SDate: any;
  ShowTimerData = 0 + 'D :' + 0 + 'H :' + 0 + 'M';
  CurrentName: any;
  AllAlias = [];
  errorshow = false;
  perfectShow: boolean = false;
  time_zone: any;
  constructor(
    public LoginflowService: LoginflowService,
    public service: ServicesService,
    public spinner: NgxSpinnerService,
    private formBuilder: FormBuilder,
    public auth: AuthserviceService,
    public router: Router,
    public ScheduleserviceService: ScheduleserviceService,
    private route: ActivatedRoute,
  ) {
    const snapshot: RouterStateSnapshot = this.router.routerState.snapshot;
    var setlogin = this.auth.isLoggedIn();
    if (!setlogin) {
      if (snapshot.url == "/sidenav/studentprofile") {
        this.router.navigate(['login']);
        this.spinner.hide()
      } else {
        this.router.navigate(['login'], {
          queryParams: { returnUrl: snapshot.url },
        });
        this.spinner.hide()
      }
    }
    else {
      this.route.params.subscribe(async (params) => {
        try {
          if (params['id']) {
            this.auth.getAuthenticatedUser().getSession(async (err, session) => {
              if (err) {
                this.router.navigate(['/login']);
              } else {
                var token = session
                let overDue_notification = JSON.parse(atob(decodeURIComponent(params['id'])));
                let overDue_notification_data = {
                  "user_id": overDue_notification.user_id,
                  "overdue_notification": overDue_notification.overdue_notification,
                  "cohort_id": overDue_notification.cohort_id
                }
                await this.LoginflowService.overdue_notification_stop(overDue_notification_data, token).then((data) => {
                  if (data[0].status == 200) {
                    this.openPage('UserSetting');
                  }
                });
              }
              this.spinner.hide();
            });
          }

        } catch (error) { }
      });
    }
    this.service.headershow = true;
    this.service.SearchValue = true;
    var access = window.localStorage.getItem('accessitem');
    if (access) {
      var set = JSON.parse(<string>access);
      if (set) {
        this.service.access.CATaccess = set.CAT_access ? true : false;
        this.service.access.Knowaccess = set.KA_access ? true : false;
        this.service.access.Practiceaccess = set.PT_access ? true : false;
        this.service.access.livechat_access = set.livechat_access ? true : false;
      }
    }
  }
  async ngOnInit() {
    this.service.headerset = {
      dashboard: false,
      studyguuide: false,
      knowledge: false,
      practice: false,
      cat: false,
      datestring: false,
      CATresult: false,
      CATQue: false,
      PracticeResult: false,
      Practiceques: false,
      studentprofile: true,
      knowques: false,
      knowresult: false,
      resource: false,
      liveSupport: false
    };

    setTimeout(() => {
      this.service.title =
        "<p class='HeaderUser'>Student Profile <span></span></p>";
    }, 0);
    this.UpdateForm = this.formBuilder.group({
      FirstName: ['', Validators.required],
      Nickname: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
      scduledate: [''],
      timezone: ['', Validators.required]
    });
    var data = localStorage.getItem('userdetails');
    if (data != undefined || data != null || data != '') {
      this.data = JSON.parse(<string>data);
      this.name = this.data.aliasname ? this.data.aliasname : this.data.name;
      this.imgurl = this.data.avatar_url;
      this.FirstName = this.data.name ? this.data.name : '';
      this.Nickname = this.data.aliasname ? this.data.aliasname : '';
      this.Email = this.data.email ? this.data.email : '';
      this.CurrentName = this.data.aliasname ? this.data.aliasname : '';

      if (this.data.schedule_date) {
        this.SDate = this.data.schedule_date;
      };
      this.time_zone = this.data.user_time_zone ? JSON.parse(this.data.user_time_zone) : this.auth.currentTimeZone();
    }
    this.spinner.show();
    await this.getCurrentClassExamDate()
    await this.getAllAlias();
    this.spinner.hide();
  }
  async getCurrentClassExamDate() {
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();
        this.router.navigate(['/login']);
      } else {
        var token = session
        var userId = localStorage.getItem('CisspUserId');
        var cer_id = localStorage.getItem('CisspCourseId');
        var cohort_id = localStorage.getItem('cohort_id');
        await this.ScheduleserviceService.getSelfSchedule(
          userId,
          cer_id,
          cohort_id,
          token
        ).then((data) => {
          if (data[0].status == 200) {
            var list = JSON.parse(<string>data[0].json);
            if (list.data.length > 0) {
              this.SDate = list.data[0].exam_date;
              this.Counter(this.SDate);
            }
          }
        });
      }
      this.spinner.hide();
    });
  }
  onChangeInput() {
    this.disableBtn = false;
  }
  async onChangeDateInput(type: string, event: MatDatepickerInputEvent<Date>) {
    this.disableBtn = false;
  }
  async getAllAlias() {
    await this.LoginflowService.getAllAlias().then((data) => {
      if (data[0].status == 200) {
        var list = JSON.parse(<string>data[0].json);
        list.data.forEach((element) => {
          this.AllAlias.push(element.aliasname.toLowerCase().trim());
        });
      }
    });
  }
  Counter(SDate) {
    var date = new Date(SDate).toISOString();
    let me = this;
    var x = setInterval(function () {
      var now = new Date().getTime();
      var countDownDate = new Date(date).getTime();
      var distance = countDownDate - now;
      var days = Math.floor(distance / (1000 * 60 * 60 * 24));
      var hours = Math.floor(
        (distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
      );
      var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = Math.floor((distance % (1000 * 60)) / 1000);
      var dateset = '';
      if (days < 0 || hours < 0 || minutes < 0) {
        dateset = '0D :0H :0M';
      } else {
        dateset = days + 'D :' + hours + 'H :' + minutes + 'M';
      }
      me.ShowTimerData = dateset;
      if (distance < 0) {
        clearInterval(x);
      }
    }, 1000);
  }
  get f() {
    return this.UpdateForm.controls;
  }
  openPage(page) {
    this.ProfileSetting = false;
    this.UserSetting = false;
    this.ChangePassword = false;
    this.Twofasetting = false;
    this.Myenrollments = false;
    if (page == 'ProfileSetting') this.ProfileSetting = true;
    else if (page == 'UserSetting') this.UserSetting = true;
    else if (page == 'ChangePassword') this.ChangePassword = true;
    else if (page == 'Twofasetting') this.Twofasetting = true;
    else if (page == 'Myenrollments') this.Myenrollments = true;
  }
  reset() {
    this.disableBtn = true;
    var data = localStorage.getItem('userdetails');
    if (data != undefined || data != null || data != '') {
      this.data = JSON.parse(<string>data);
      this.name = this.data.aliasname ? this.data.aliasname : this.data.name;
      this.imgurl = this.data.avatar_url;
      this.FirstName = this.data.name ? this.data.name : '';
      this.Nickname = this.data.aliasname ? this.data.aliasname : '';
      this.CurrentName = this.data.aliasname ? this.data.aliasname : '';
      this.Email = this.data.email ? this.data.email : '';
      this.SDate = this.data.schedule_date ? this.data.schedule_date : '';
      this.time_zone = this.data.user_time_zone ? JSON.parse(this.data.user_time_zone) : this.auth.currentTimeZone();
    }
  }
  async save() {
    this.disableBtn = true;
    this.submitted = true;
    if (this.UpdateForm.valid) {
      await this.spinner.show();
      await this.auth
        .getAuthenticatedUser()
        .getSession(async (err, session) => {
          if (err) {
            await this.spinner.hide();
            this.router.navigate(['/login']);
          } else {
            var token = session
            var userId = localStorage.getItem('CisspUserId');
            var cer_id = localStorage.getItem('CisspCourseId');
            var cohort_id = localStorage.getItem('cohort_id');
            await this.LoginflowService.saveExamDate(userId, cer_id, cohort_id, this.SDate, token).then(
              async (data) => {
              },
              () => {
                this.spinner.hide();
              }
            );
            var onboardigdata = {
              email: this.Email,
              user_time_zone: JSON.stringify(this.time_zone)
            };
            await this.LoginflowService.updateUserByEmail(onboardigdata).then((onboardingFlowRes) => {
              if (onboardingFlowRes[0].status == 200) { }
            });
            await this.LoginflowService.updateUser(this.data.id, this.FirstName, this.Nickname, this.SDate, token).then(
              async (data) => {
                if (data[0].status == 200) {
                  var list = JSON.parse(<string>data[0].json);
                  localStorage.setItem(
                    'CisspUserId',
                    JSON.stringify(list.data.id)
                  );
                  localStorage.setItem(
                    'userdetails',
                    JSON.stringify(list.data)
                  );
                  var datas = localStorage.getItem('userdetails');
                  if (datas != undefined || datas != null || datas != '') {
                    this.data = JSON.parse(<string>datas);
                    this.name = this.data.aliasname
                      ? this.data.aliasname
                      : this.data.name;
                    this.imgurl = this.data.avatar_url;
                    this.FirstName = this.data.name ? this.data.name : '';
                    this.Nickname = this.data.aliasname
                      ? this.data.aliasname
                      : '';
                    this.Email = this.data.email ? this.data.email : '';
                    this.time_zone = this.data.user_time_zone ? JSON.parse(this.data.user_time_zone) : this.auth.currentTimeZone();
                    var al = document.getElementById('headerAliasName');
                    al.innerHTML = "<span>Welcome,</span>" + this.name;
                  }
                  await this.service.ShowSuccess("User update successfully!")
                  await this.spinner.hide();
                } else {
                  await this.spinner.hide();
                }
              },
              () => {
                this.spinner.hide();
              }
            );
          }
        });
    }
  }
  checkAlias() {
    this.disableBtn = false;
    if (this.AllAlias.includes(this.Nickname.toLowerCase().trim())) {
      if (this.Nickname != this.CurrentName) {
        this.errorshow = true;
        this.perfectShow = false;
      }
      else {
        this.errorshow = false;
        this.perfectShow = false;
      }
    } else {
      this.errorshow = false;
      if (
        this.Nickname.trim() != null &&
        this.Nickname.trim() != '' &&
        this.Nickname.trim() != undefined
      ) {
        this.perfectShow = true;
      } else {
        this.perfectShow = false;
      }
    }
  }
  retuey() {
    window.location.reload();
  }
}