import { Component, OnInit } from '@angular/core';
import { ServicesService } from '../../services.service';
import { Router, ActivatedRoute } from '@angular/router';
import { NgxSpinnerService } from 'ngx-spinner';
import html2pdf from 'html2pdf.js';
import { AuthserviceService } from '../../authservice.service';
import { CourseserviceService } from '../../services/course/courseservice.service';
import { CryptoService } from 'src/app/services/crypto/crypto.service';
import { LoginflowService } from 'src/app/data/loginflow.service';

@Component({
  selector: 'app-myenrollments',
  templateUrl: './myenrollments.component.html',
  styleUrls: ['./myenrollments.component.scss'],
})
export class MyenrollmentsComponent implements OnInit {
  Email: any;
  public data: any;
  subject = []
  RestorePurchasePopup: boolean = false;
  TermsOfServicePopup: boolean = false;
  PaymentAccess: boolean = false;
  courselist = [];
  availabelcourse = [];
  AvailableCourse = false;
  Enrollnofound = false;
  userid: any;
  ShowTimerData = 0 + 'D :' + 0 + 'H :' + 0 + 'M';
  IsUpgradeModal: boolean = false;
  domainsData = [];
  time_zone: any;
  content: any = "HELLO";
  constructor(
    public auth: AuthserviceService,
    public service: ServicesService,
    public spinner: NgxSpinnerService,
    public ActiveRoute: ActivatedRoute,
    public router: Router,
    public CourseserviceService: CourseserviceService,
    private crypto: CryptoService,
    public LoginflowService: LoginflowService,
  ) { }

  async ngOnInit(): Promise<void> {
    var data = JSON.parse(localStorage.getItem('userdetails'));
    this.time_zone = data.user_time_zone ? JSON.parse(data.user_time_zone) : this.auth.currentTimeZone();
    this.spinner.show();
    await this.listCourses();
  }
  async mailsend(item) {
    var data = localStorage.getItem('userdetails');
    var username = '';
    if (data != undefined || data != null || data != '') {
      this.data = JSON.parse(<string>data);
      this.Email = this.data.email ? this.data.email : '';
      username = this.data.name ? this.data.name : '';
    }
    var user_id = localStorage.getItem('CisspUserId');
    let certificate = this.crypto.enc(JSON.stringify({
      "user_id": user_id,
      "cohort_id": item.cohort_id,
      "cohort_name": item.cohort_name + " (" + item.short_name + ")",
      "name": username,
      "expire_Date": item.expire_Date
    }));
    this.router.navigate([`certificate/${certificate}`]);

  }

  RestorePurchase() {
    this.RestorePurchasePopup = true;

  }
  TermsOfService() {
    this.TermsOfServicePopup = true;
  }
  close() {
    this.TermsOfServicePopup = false;
    this.RestorePurchasePopup = false;
  }
  Counter() {
    var data = JSON.parse(localStorage.getItem('userdetails'));
    if (data.schedule_date) {
      var date = new Date(data.schedule_date).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 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);
    }
  }
  async listCourses() {
    this.userid = localStorage.getItem('CisspUserId');
    this.courselist = [];
    this.availabelcourse = [];
    try {
      await this.auth
        .getAuthenticatedUser()
        .getSession(async (err, session) => {
          if (err) {
            await this.spinner.hide();
            this.router.navigate(['/login']);
          } else {
            var token = session
            await this.CourseserviceService.knowassquecource(
              this.userid,
              token
            ).then(async (data) => {
              if (data[0].status == 200) {
                var list = JSON.parse(<string>data[0].json);
                this.courselist = list.data;
                this.courselist.forEach(element => {
                  element['include'] = element.opt_in;
                  element['expire_Date'] = this.auth.ConvertDateDDFormat(element.expire_on, this.time_zone.nameValue, "MMM DD, YYYY");
                  if (element.exam_date != null && element.exam_date != "") {
                    var now = this.auth.ConvertAnyTimeZoneToCurrentZone(new Date(), this.time_zone.nameValue).getTime();
                    var countDownDate = this.auth.ConvertAnyTimeZoneToCurrentZone(element.exam_date, this.time_zone.nameValue).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 dateset = '';
                    if (days < 0 || hours < 0 || minutes < 0) {
                      dateset = '0D :0H :0M';
                    } else {
                      dateset = days + 'D :' + hours + 'H :' + minutes + 'M';
                    }

                  }
                  else {
                    dateset = '0D :0H :0M';
                  }
                  element["ShowTimerData"] = dateset;
                  element['Access'] = "(" + element.access_duration + "-Days access" + (element.course_type == "subscription" ? " - Auto renews)" : ")");

                  element['certiDownloadPercentage'] = (element.cat_per + element.know_per + element.practice_per) / 3;
                  let overall = localStorage.getItem('overall')
                  if (overall == '100') {
                    element['certiDownloadPercentage'] = 100
                  }
                });
                await this.cohortexpireDate()
              }
              await this.spinner.hide();
            });
          }
        });
    } catch (e) {
      await this.spinner.hide();
    }
  }
  showUpgradeModal() {
    this.IsUpgradeModal = true;
  }
  async changeInclude(item) {
    try {
      this.spinner.show();
      let userid = localStorage.getItem('CisspUserId');
      let opt = item.include == "1" ? "0" : "1";
      var onboardigdata = {
        user_id: userid,
        cohort_id: item.cohort_id,
        opt_in: opt
      };
      await this.LoginflowService.update_onboarding_flow(onboardigdata).then((onboardingFlowRes) => {
        if (onboardingFlowRes[0].status == 200) {
          this.service.ShowSuccess("Saved successfully");
        }
        else {
          this.router.navigate(['/login']);
          this.spinner.hide();
        }
      })
    } catch (e) {
      await this.spinner.hide();
      this.service.ShowError(e.meassage);
    }

  }

  async update_onboarding_flow(opt_in) {
    let user_id = localStorage.getItem('CisspUserId');
    var onboardigdata = {
      user_id: user_id,
      cohort_id: this.data.cohort_id,
      opt_in: opt_in
    };

    await this.LoginflowService.update_onboarding_flow(onboardigdata).then((onboardingFlowRes) => {
      if (onboardingFlowRes[0].status == 200) {
        var list = JSON.parse(<string>onboardingFlowRes[0].json);
      }
      else {
        this.router.navigate(['/login']);
      }
    })
  }
  async viewDashboard(item) {
    this.service.courseid = item.certi_id;
    await this.getResult(item.certi_id, item.cohort_id);
    var chort_id_check = localStorage.getItem('cohort_id');
    localStorage.setItem('CisspCourseId', item.certi_id);
    localStorage.setItem('cohort_id', item.cohort_id);
    localStorage.setItem('overall', item.percentage);
    window.localStorage.setItem('accessitem', JSON.stringify(item.access));
    var uri = this.ActiveRoute.snapshot.queryParams['returnUrl'] || null;
    if (uri && !chort_id_check) {
      this.router.navigateByUrl(uri);
    }
    else {
      if (item.access.show_resources == 1) {
        await this.router.navigate([`/sidenav/dashboard`]);
      } else {
        await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
          if (err) {
            this.spinner.hide();
            this.router.navigate(['/login']);
          } else {
            var token = session
            let user_id = localStorage.getItem('CisspUserId');
            this.spinner.show();
            await this.CourseserviceService.updateResourceShow(user_id, token).then(async (data) => {
              this.spinner.hide();
              await this.router.navigate([`/sidenav/resource`]);
            })
          }
        })
      }
    }
  }
  async getResult(cid, cohort_id) {
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        this.spinner.hide();
        this.router.navigate(['/login']);
      } else {
        var token = session
        let user_id = localStorage.getItem('CisspUserId');
        this.spinner.show();
        await this.CourseserviceService.getDashboardPercentage(
          user_id,
          cid,
          cohort_id,
          token
        ).then(async (data) => {
          if (data[0].status == 200) {
            var list = JSON.parse(<string>data[0].json);
            this.domainsData = list.data;

            let sum = 0;
            let i = 0;
            let w = [9, 11, 12, 12, 12, 12, 12, 12];
            this.domainsData.forEach((element) => {
              element.weight = w[i];
              i++;
              sum += element.totalPro;
            });
            localStorage.setItem(
              'domainsData',
              JSON.stringify(this.domainsData)
            );
            this.spinner.hide();
          } else {
            this.spinner.hide();
          }
        });
      }
    });
  }

  async cohortexpireDate() {
    this.courselist.forEach(async element => {
      await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        if (err) {
          await this.spinner.hide();
          this.router.navigate(['/login']);
        } else {
          var token = session
          this.spinner.show();
          await this.CourseserviceService.cohortsCertificateExpireDate(this.userid, element.cohort_id, token).then(async (certidata) => {
            var certilist = JSON.parse(<string>certidata[0].json);
            if (element.course_type == 'subscription' || element.course_type == 'onetime') {
              if (new Date(element.expire_on) < new Date()) {
                element['certiDownloadPercentage'] = 100;
                element['expire_Date'] = this.auth.ConvertDateDDFormat(certilist.data[0].expire_date, this.time_zone.nameValue, "MMM DD, YYYY");
              }
            } else if (element.course_type == null || element.course_type == "") {
              if (new Date(certilist.data[0].expire_date) < new Date()) {
                element['certiDownloadPercentage'] = 100;
                element['expire_Date'] = this.auth.ConvertDateDDFormat(certilist.data[0].expire_date, this.time_zone.nameValue, "MMM DD, YYYY");
              }
            } else {
              if (new Date(element.expire_on) < new Date()) {
                element['certiDownloadPercentage'] = 100;
                element['expire_Date'] = this.auth.ConvertDateDDFormat(certilist.data[0].expire_date, this.time_zone.nameValue, "MMM DD, YYYY");
              }
            }
          })
          this.spinner.hide();
        }
      });
    });

  }
  gotoStudentReport(item) {
    var userdetails = JSON.parse(localStorage.getItem('userdetails'));
    var data = {
      user_id: this.userid,
      cohort_id: item.cohort_id,
      cohort_name: item.cohort_name,
      user_name: userdetails.name,
      email: userdetails.email,
    };
    var id = btoa(JSON.stringify(data));
    id = encodeURIComponent(id);
    this.router.navigate([`/studentreport/${id}`]);
  }

  printReport(item) {

    var data = localStorage.getItem('userdetails');
    var username = '';
    if (data != undefined || data != null || data != '') {
      this.data = JSON.parse(<string>data);
      this.Email = this.data.email ? this.data.email : '';
      username = this.data.name ? this.data.name : '';
    }
    var cohort_name = item.cohort_name + " (" + item.short_name + ")"
    var expire_Date = item.expire_Date
    var pdfname = item.cohort_name + " Certificate.pdf"

    const element = `
    <div class="main-report-div" style="box-sizing: border-box;margin: 0 auto;" id="componentID">
      <div class="main-cartificate" style="background: white;height: 802px;border: 7px solid #0b1130;position: relative;margin: 0 auto;" id="printable">
        <div class="head-div" style="height: 274px;background-repeat: no-repeat;background-size: 100% 100%;background: linear-gradient(120deg, #fa007e63 50%, #01025e 100%);position: relative;display: flex;justify-content: center;">
          <div class="title" style="display: flex;align-items: flex-end;justify-content: center;width: 100%;background: linear-gradient(0deg, #00000087 10%, transparent 31%);padding-bottom: 27px;">
            <h2 style="margin: 0;font-size: 44px;color: #fff;">Certificate of Completion</h2>
          </div>
        </div>
          <div class="label" style="position: absolute;top: 215px;right: 50px;">
            <div class="label-img" style="color: #fff;width: 170px;">
              <img src="../../assets/Label.png" alt="Label" style="display: block;width: 100%;position: absolute;">
              <h1 style="top: 40px;font-size: 60px;text-align: center;line-height: 21px;z-index: 99;position: relative;font-weight: inherit;">
                40 
                <br>
                <span style="font-size: 17px;">CPE Hours</span>
              </h1>
            </div>
          </div>
          <div class="body-div" style="margin-top: 50px;">
            <div class="student-name" style="margin: 0 auto;text-align: center;">
              <p style=" margin: 0;font-size: 16px;color: #2e3d87;display: block;font-family: inherit;font-weight: normal;">This certificate is awarded to</p>
              <h1 style="display: inline-block;padding: 15px 30px 20px;font-size: 50px;font-weight: 500;line-height: 1;margin: 5px 0;color: #e86570;background-size: 100%;border-bottom: 2px solid #979797;">Flexxon</h1>
              <span style="display: block;font-size: 16px;color: #2e3d87;padding: 20px 0 10px;">for successfully completing </span>
              <h3 style="font-size: 26px;color: #2e3d87;margin: 0;font-weight: 500;">${cohort_name}</h3>
            </div>
          </div>
          <div class="footer-div" style="background: #fff;padding-top: 6em;width: 98%;bottom: 16px;margin: 30px 0;display: flex;align-items: center;">
              <div class="date" style="width: 33%;text-align: center; padding-top: 15px;">
                  <h1 style="margin: 0; color: #000;font-size: 19px;padding: 10px 0;">${expire_Date}</h1>
                  <span style="font-size: 14px;color: #2e3d87;border-top: 1px solid #979797;padding: 10px 30px 0;font-weight: 800;font-family: "Roboto";">Date of Completion</span>
              </div>
              <div class="logo" style="width: 33%;text-align: center;">
                  <img src="../../assets/footer-logo.png" alt="logo" style="width: 150px;">
              </div>
              <div class="student-names" style="width: 33%;text-align: center; padding-top: 15px;">
                  <h1 style="margin: 0;"><img style="width:60px; hight:55px" src="../../assets/certificate/sign.png"></h1>
                  <span style="font-size: 14px;color: #2e3d87;border-top: 1px solid #979797;padding: 10px 30px 0;font-weight: 800;font-family: "Roboto";">Authorizer Signature</span>
              </div>
          </div>
      </div>
    </div>
    `
    var opt = {
      margin: 0,
      filename: pdfname,
      image: { type: 'jpeg', quality: 0.99 },
      html2canvas: { scale: 1.2 },
      jsPDF: { unit: 'in', format: 'letter', orientation: 'landscape' }
    };
    html2pdf().set(opt).from(element).save();
  }
}