import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import Swal from 'sweetalert2/dist/sweetalert2.js'
import { ServicesService } from '../../services.service';
import { NgxSpinnerService } from "ngx-spinner";
import { Router, ActivatedRoute } from '@angular/router';
import { MatSort } from '@angular/material/sort';
import { AuthorizationService } from '../../service/authorization.service';
import { FormBuilder, FormGroup, Validators, FormArray } from '@angular/forms';
import { PracticeService } from '../../services/practice/practice.service';
import * as ClassicEditor from '@blowstack/ckeditor5-full-free-build';
import * as XLSX from 'xlsx';
import { ExcelService } from 'src/app/services/excelservices/excel.service';

@Component({
  selector: 'app-practicequestion',
  templateUrl: './practicequestion.component.html',
  styleUrls: ['./practicequestion.component.scss']
})
export class PracticequestionComponent implements OnInit {

  displayedColumns: string[] = ['srno', 'certificate_name', "domin_name", 'subdomain_name', 'topic_name', 'practice_name', 'title', 'actions'];
  dataSource: MatTableDataSource<courselist>;
  Search: any;
  addPracticeQua: boolean = false


  id: any;
  IsUpdate: boolean = false;
  public PraacticeQueForm: FormGroup;
  Domainname: any;
  subdomainname: any;
  Topicname: any;
  title: any;
  option1: any;
  option2: any;
  option3: any;
  option4: any;
  CorrectAnswer: any;
  Type: any;
  Explanation: any;
  ListCerficateData = [];
  Domain = [];
  filterDomain = [];
  SubDomain = [];
  filterSubDomain = [];
  Topic = [];
  filterTpoic = [];
  testdata = [];
  filterTestData = [];
  test_id: any;
  loglist = [];
  CertificateName: any;
  Certificates = [];
  isBulkUpload: boolean = false;
  files: File[] = [];
  myEvent: any;
  progress: any = 0;
  selectBulkupload: boolean = false;
  selectprogress: boolean = false;
  oldAuditValueArray = { "Certificate": "", "Domain": "", "Subdomain": "", "Topic": "", "Question": "", "Answer A": "", "Answer B": "", "Answer C": "", "Answer D": "", "Answer": "", "Explanation": "", "Exam Name": "", "Difficulty": "" }
  newAuditValueArray = { "Certificate": "", "Domain": "", "Subdomain": "", "Topic": "", "Question": "", "Answer A": "", "Answer B": "", "Answer C": "", "Answer D": "", "Answer": "", "Explanation": "", "Exam Name": "", "Difficulty": "" }
  auditHistory = "";


  public Editor = ClassicEditor;
  @Input('pagination') pagination: boolean;
  @ViewChild(MatPaginator, { static: false }) set matPaginator(paginator: MatPaginator) {
    if (this.pagination) {
      this.dataSource.paginator = paginator;
    }
  }
  @ViewChild(MatSort, { static: true }) sort: MatSort;

  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;

  constructor(public practiceService: PracticeService, public ActiveRoute: ActivatedRoute, public auth: AuthorizationService, public fb: FormBuilder, public router: Router, public spinner: NgxSpinnerService, public service: ServicesService, private excelService: ExcelService) {
    var setlogin = this.auth.isLoggedIn();
    if (!setlogin) {
      this.router.navigate(['/login']);
    }
  }

  addNewPracticeQua() {
    this.addPracticeQua = true
  }

  closeModal() {
    this.addPracticeQua = false;
    this.IsUpdate = false;
    this.test_id = "";
    this.Domainname = "";
    this.subdomainname = "";
    this.Topicname = "";
    this.title = "";
    this.option1 = "";
    this.option2 = "";
    this.option3 = "";
    this.option4 = "";
    this.CorrectAnswer = "";
    this.Type = "";
    this.CertificateName = "";
    this.Explanation = "";
    this.oldAuditValueArray = { "Certificate": "", "Domain": "", "Subdomain": "", "Topic": "", "Question": "", "Answer A": "", "Answer B": "", "Answer C": "", "Answer D": "", "Answer": "", "Explanation": "", "Exam Name": "", "Difficulty": "" }
    this.newAuditValueArray = { "Certificate": "", "Domain": "", "Subdomain": "", "Topic": "", "Question": "", "Answer A": "", "Answer B": "", "Answer C": "", "Answer D": "", "Answer": "", "Explanation": "", "Exam Name": "", "Difficulty": "" }
    this.auditHistory = "";
  }

  async ngOnInit() {
    this.PraacticeQueForm = this.fb.group({
      CertificateName: ['', Validators.required],
      test_id: ['', Validators.required],
      Domainname: ['', Validators.required],
      subdomainname: ['', Validators.required],
      Topicname: ['', Validators.required],
      title: ['', Validators.required],
      option1: ['', Validators.required],
      option2: ['', Validators.required],
      option3: ['', Validators.required],
      option4: ['', Validators.required],
      CorrectAnswer: ['', Validators.required],
      Type: ['', Validators.required],
      Explanation: ['', Validators.required],
    });
    await this.spinner.show();
    try {
      this.test_id = "";
      this.Domainname = "";
      this.subdomainname = "";
      this.Topicname = "";
      this.title = "";
      this.option1 = "";
      this.option2 = "";
      this.option3 = "";
      this.option4 = "";
      this.CorrectAnswer = "";
      this.Type = "";
      this.CertificateName = "";
      await this.listPracticalQues();
      await this.listPrcTest();
      await this.GetAllDropdown();
      await this.ActiveRoute.params.subscribe(async (params) => {
        try {
          var id = JSON.parse(atob(params['id']));
          if (this.dataSource && this.dataSource.data && this.dataSource.data.length > 0) {
            await this.dataSource.data.forEach(async (element) => {
              if (element.id == id) {
                await this.edit(element);
              }
            });
          }

        } catch (error) {
          this.router.navigate(['main/PracticetestQuestion']);
        }
      });

      await this.spinner.hide();
    }
    catch (e) {
      await this.spinner.hide();
      this.service.ShowError(e.message);
    }
  }

  async certificatechange(ev) {
    const val = ev.target.value;
    if (val && val.trim() != '') {
      this.Domain = this.filterDomain.filter((data) => {
        return (

          data.certi_id == val
        );
      })
      this.testdata = this.filterTestData.filter((data) => {
        return (
          data.certi_id == val
        );
      })
      this.Domainname = "";
      this.subdomainname = "";
      this.Topicname = ""
    }
    else {
      this.Domainname = "";
      this.subdomainname = "";
      this.Topicname = ""
      this.Domain = this.filterDomain;
    }
  }
  async domainchange(ev) {
    const val = ev.target.value;
    if (val && val.trim() != '') {
      this.SubDomain = this.filterSubDomain.filter((itemset) => {
        return (
          itemset.d_id == val
        );

      });

      this.Topicname = '';
      this.subdomainname = '';
    } else {
      this.Domainname = '';
      this.subdomainname = '';
      this.SubDomain = this.filterSubDomain;
    }
  }
  async SubDomainchange(ev) {
    const val = ev.target.value;
    if (val && val.trim() != '') {
      this.Topic = this.filterTpoic.filter((itemset) => {
        return (
          itemset.sd_id == val
        );
      });
      this.Topicname = '';
    } else {
      this.Topicname = '';
      this.Topic = this.filterTpoic;
    }
  }
  markFormTouched(group: FormGroup | FormArray) {
    Object.keys(group.controls).forEach((key: string) => {
      const control = group.controls[key];
      if (control instanceof FormGroup || control instanceof FormArray) { control.markAsTouched(); this.markFormTouched(control); }
      else { control.markAsTouched(); };
    });
  };
  async GetAllDropdown() {
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();
        this.router.navigate(['/login']);
      }
      else {
        var token = ''
        await this.service.GetAllDropdown(token).then(async (data) => {
          if (data[0].status == 200) {
            var list = JSON.parse(<string>data[0].json);
            debugger;
            this.ListCerficateData = list.data.Certificate;
            this.Topic = list.data.Topic;
            this.filterTpoic = list.data.Topic;
            this.SubDomain = list.data.SubDomain;
            this.Domain = list.data.Domain;
            this.filterDomain = list.data.Domain;
            this.filterSubDomain = list.data.SubDomain;
            this.Certificates = list.data.Certificate;

          }
        })
      }
    });
  }
  async delete(item) {
    Swal.fire({
      title: 'Are you sure?',
      text: "You want to delete!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Delete'
    }).then(async (result) => {
      if (result.value) {
        await this.spinner.show();
        try {
          await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
            if (err) {
              await this.spinner.hide();

              this.router.navigate(['/login']);
            }
            else {

              var token = ''
              await this.practiceService.DeletePracticeQuestion(item.id, token).then(async (value) => {
                if (value[0].status == 200) {
                  var list = JSON.parse(<string>value[0].json);
                  var e = window.localStorage.getItem("adminUser");
                  if (e == null || e == undefined || e == "") {
                    e = 'admin';
                  }
                  var desc = "<span> " + item.practice_name + "</span> Practice Question is deleted by <span> " + e + "</span>";
                  await this.service.addAdminLogs(desc, "practicetestque", this.id, token);
                  await this.listPracticalQues();
                  await this.spinner.hide();
                  Swal.fire(
                    list.message,
                    'Practice Question has been deleted.',
                    'success'
                  )
                }
                else {
                  var list = JSON.parse(<string>value[0].json);
                  await this.spinner.hide();
                  this.service.ShowError(list.message);
                }

              })

            }
          });

        }
        catch (e) {
          await this.spinner.hide();
          this.service.ShowError(e.message);

        }
      }
    })
  }
  async listPrcTest() {
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();

        this.router.navigate(['/login']);
      }
      else {

        var token = ''
        await this.practiceService.ListPracticeTest(token).then(async (data) => {
          this.testdata = [];
          this.filterTestData = [];
          if (data[0].status == 200) {
            var list = JSON.parse(<string>data[0].json);
            this.testdata = list.data;
            this.filterTestData = list.data;
          }
        })

      }
    });

  }
  async listPracticalQues() {
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();

        this.router.navigate(['/login']);
      }
      else {

        var token = ''

        const users: courselist[] = [];
        await this.practiceService.ListPracticeQuestion(token).then(async (data) => {
          if (data[0].status == 200) {
            var list = JSON.parse(<string>data[0].json);
            var srno = 0;
            await list.data.forEach(async (element) => {
              srno = srno + 1;
              await users.push({
                "srno": srno,
                "id": element.id,
                "test_id": element.test_id,
                "title": element.title,
                "first_choice": element.first_choice,
                "second_choice": element.second_choice,
                "third_choice": element.third_choice,
                "fourth_choice": element.fourth_choice,
                "answer": element.answer,
                "type": element.type,
                "d_id": element.d_id,
                "topic_id": element.topic_id,
                "ref_link": element.ref_link,
                "youtube_link": element.youtube_link,
                "bookpage_no": element.bookpage_no,
                "blog_url": element.blog_url,
                "createdAt": element.createdAt,
                "updatedAt": element.updatedAt,
                "domin_name": element.domain.domin_name,
                "subdomain_name": element.subdomain.subdomain_name,
                "topic_name": element.topic.topic_name,
                "practice_name": element?.practicetest?.practice_name,
                "sd_id": element.sd_id,
                "point": element.point,
                "description": element.description,
                "certi_id": element.certi_id,
                "certificate_name": element.certificate ? element.certificate.certificate_name : ""
              })
            });
            this.dataSource = new MatTableDataSource(users);
            this.dataSource.sort = this.sort;
            this.dataSource.paginator = this.paginator;
            this.filter();
            this.pagination = true;
          }

        })
      }
    });

  }
  async edit(item) {
    this.loglist = [];
    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 = ''
        await this.service.get_logs("practicetestque", item.id, token).then(async (value) => {
          if (value[0].status == 200) {
            var list = JSON.parse(<string>value[0].json);

            this.loglist = list.data;
            await this.spinner.hide();

          }
          else {
            var list = JSON.parse(<string>value[0].json);
            await this.spinner.hide();

            this.service.ShowError(list.message);
          }

        }, err => {
          this.spinner.hide();
        })
      }
    })
    this.CertificateName = item.certi_id;
    this.addPracticeQua = true;
    this.IsUpdate = true;
    this.id = item.id;
    this.test_id = item.test_id;
    this.Domainname = item.d_id;
    this.subdomainname = item.sd_id;
    this.Topicname = item.topic_id;
    this.title = item.title;
    this.option1 = item.first_choice;
    this.option2 = item.second_choice;
    this.option3 = item.third_choice;
    this.option4 = item.fourth_choice;
    this.CorrectAnswer = item.answer;
    this.Type = item.type;
    this.Explanation = item.description;

    this.Domain = this.filterDomain.filter(x => x.certi_id == this.CertificateName);
    this.SubDomain = this.filterSubDomain.filter(x => x.d_id == this.Domainname);
    this.Topic = this.filterTpoic.filter(x => x.sd_id == this.subdomainname)
    this.oldAuditValueArray = { "Certificate": this.ListCerficateData.find(x => x.id == this.CertificateName) ? this.ListCerficateData.find(x => x.id == this.CertificateName).certificate_name : '', "Domain": this.filterDomain.find(x => x.id == this.Domainname) ? this.filterDomain.find(x => x.id == this.Domainname).domin_name : '', "Subdomain": this.filterSubDomain.find(x => x.id == this.subdomainname) ? this.filterSubDomain.find(x => x.id == this.subdomainname).subdomain_name : '', "Topic": this.filterTpoic.find(x => x.id == this.Topicname) ? this.filterTpoic.find(x => x.id == this.Topicname).topic_name : '', "Question": this.title, "Answer A": this.option1, "Answer B": this.option2, "Answer C": this.option3, "Answer D": this.option4, "Answer": this.CorrectAnswer == 1 ? "Answer A" : (this.CorrectAnswer == 2 ? "Answer B" : (this.CorrectAnswer == 3 ? "Answer C" : (this.CorrectAnswer == 4 ? "Answer D" : ""))), "Explanation": this.Explanation, "Exam Name": this.filterTestData.find(x => x.id == this.test_id).practice_name ? this.filterTestData.find(x => x.id == this.test_id).practice_name : '', "Difficulty": this.Type }

  }
  async filter() {
    this.dataSource.filter = this.Search;
    if (this.pagination) {
      this.dataSource.paginator._changePageSize(this.dataSource.paginator.pageSize);
    }
  }
  async onSubmit() {
    this.markFormTouched(this.PraacticeQueForm);
    if (this.PraacticeQueForm.valid) {
      await this.spinner.show();
      try {
        await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
          if (err) {
            await this.spinner.hide();
            this.router.navigate(['/login']);
          }
          else {
            var token = ''
            await this.practiceService.AddPracticeQuestion(this.test_id, this.title, this.option1, this.option2, this.option3, this.option4, this.CorrectAnswer, this.Type, this.Domainname, this.subdomainname, this.Topicname, token, this.Explanation, 0, this.CertificateName).then(async (value) => {
              if (value[0].status == 200) {
                var list = JSON.parse(<string>value[0].json);
                var e = window.localStorage.getItem("adminUser");
                if (e == null || e == undefined || e == "") {
                  e = 'admin';
                }
                var desc = "<span> " + this.title + "</span> Practice Question is added by <span> " + e + "</span>";
                await this.service.addAdminLogs(desc, "practicetestque", list.data.id, token);
                await this.listPracticalQues();
                this.closeModal();
                await this.spinner.hide();
                this.service.ShowSuccess(list.message);
              }
              else {
                var list = JSON.parse(<string>value[0].json);
                await this.spinner.hide();
                this.service.ShowError(list.message);
              }
            })

          }
        });

      }
      catch (e) {
        await this.spinner.hide();
        this.service.ShowError(e.message);

      }
    }
  }
  async UpdatePracticeQue() {
    await this.spinner.show();
    this.markFormTouched(this.PraacticeQueForm);
    if (this.PraacticeQueForm.valid) {
      try {
        await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
          if (err) {
            await this.spinner.hide();

            this.router.navigate(['/login']);
          }
          else {

            var token = ''

            await this.practiceService.UpdatePracticeQuestion(this.test_id, this.title, this.option1, this.option2, this.option3, this.option4, this.CorrectAnswer, this.Type, this.Domainname, this.subdomainname, this.Topicname, this.id, token, this.Explanation, 0, this.CertificateName).then(async (value) => {
              if (value[0].status == 200) {
                var list = JSON.parse(<string>value[0].json);
                var token = ''
                var e = window.localStorage.getItem("adminUser");
                if (e == null || e == undefined || e == "") {
                  e = 'admin';
                }
                this.newAuditValueArray = { "Certificate": this.ListCerficateData.find(x => x.id == this.CertificateName) ? this.ListCerficateData.find(x => x.id == this.CertificateName).certificate_name : '', "Domain": this.filterDomain.find(x => x.id == this.Domainname) ? this.filterDomain.find(x => x.id == this.Domainname).domin_name : '', "Subdomain": this.filterSubDomain.find(x => x.id == this.subdomainname) ? this.filterSubDomain.find(x => x.id == this.subdomainname).subdomain_name : '', "Topic": this.filterTpoic.find(x => x.id == this.Topicname) ? this.filterTpoic.find(x => x.id == this.Topicname).topic_name : '', "Question": this.title, "Answer A": this.option1, "Answer B": this.option2, "Answer C": this.option3, "Answer D": this.option4, "Answer": this.CorrectAnswer == 1 ? "Answer A" : (this.CorrectAnswer == 2 ? "Answer B" : (this.CorrectAnswer == 3 ? "Answer C" : (this.CorrectAnswer == 4 ? "Answer D" : ""))), "Explanation": this.Explanation, "Exam Name": this.filterTestData.find(x => x.id == this.test_id).practice_name ? this.filterTestData.find(x => x.id == this.test_id).practice_name : '', "Difficulty": this.Type };
                var audit = this.auth.compareAuditHist(this.oldAuditValueArray, this.newAuditValueArray);
                var desc = audit;
                var audit = this.auth.compareAuditHist(this.oldAuditValueArray, this.newAuditValueArray);
                await this.service.addAdminLogs(desc, "practicetestque", this.id, token);

                await this.listPracticalQues();
                this.closeModal();
                await this.spinner.hide();
                this.service.ShowSuccess("Question update successfully");
              }
              else {
                var list = JSON.parse(<string>value[0].json);
                await this.spinner.hide();
                this.service.ShowError(list.message);
              }
            })
          }
        });
      }
      catch (e) {
        await this.spinner.hide();
        this.service.ShowError(e.message);
      }
    }
  }

  async bulkCheckDKIM(data) {
    let response = 0;
    data.forEach(async (element) => {
      let domain = element.email.split("@")[1];
      await this.auth.verifyDKIM(domain).then(async (result) => {
        if (result[0].StatusCode == 1) {
          response = 1;
        }
      })
    });
    return response;
  }
  async openBulkUploadModal() {
    this.isBulkUpload = true;
  }
  async closeBulkUploadModal() {
    this.isBulkUpload = false;
    this.progress = 0;
    this.selectBulkupload = true;
    this.selectprogress = false;
    this.files = [];
    this.myEvent = "";
  }
  // async bulkUpload() {
  //   debugger;
  //   let workBook = null;
  //   let jsonData = null;
  //   const reader = new FileReader();
  //   const file = this.myEvent.addedFiles[0];
  //   reader.onload = async (event) => {
  //     const data = reader.result;
  //     workBook = XLSX.read(data, { type: 'binary' });
  //     jsonData = workBook.SheetNames.reduce((initial, name) => {
  //       const sheet = workBook.Sheets[name];
  //       initial[name] = XLSX.utils.sheet_to_json(sheet);
  //       return initial;
  //     }, {});
  //   }

  //   reader.readAsBinaryString(file);
  // }
  async bulkUpload() {
    let workBook = null;
    let jsonData = null;
    let sheet = [];
    const reader = new FileReader();
    const file = this.myEvent.addedFiles[0];
    reader.onload = async (event) => {
      const data = reader.result;
      workBook = XLSX.read(data, { type: 'binary' });
      jsonData = workBook.SheetNames.reduce((initial, name) => {
        const sheet = workBook.Sheets[name];
        initial[name] = XLSX.utils.sheet_to_json(sheet);
        return initial;
      }, {});
      const dataString = (jsonData);

      dataString.PracticeQuestion_sample.forEach((practicetest)=>{
        let certification_id;
        if(practicetest.certification){
          certification_id = this.ListCerficateData.find(x=> x.certificate_name == practicetest.certification).id ;
        }
        if(practicetest.certification){
          sheet.push({
            "certi_id": certification_id,
            "d_id": this.filterDomain.find(x => (x.domin_name == practicetest.domain) && (x.certi_id == certification_id)).id,
            "sd_id": this.filterSubDomain.find(x => (x.subdomain_name == practicetest.subdomain) && (x.certi_id == certification_id)).id,
            "topic_id": this.filterTpoic.find(x => (x.topic_name == practicetest.topic) && (x.certi_id == certification_id)).id,
            "test_id": this.filterTestData.find(x => (x.practice_name == practicetest.Exam) && (x.certi_id == certification_id)).id,
            "title": practicetest.question,
            "first_choice": practicetest.answer_a,
            "second_choice": practicetest.answer_b,
            "third_choice": practicetest.answer_c,
            "fourth_choice": practicetest.answer_d,
            "answer": practicetest.correct_answer,
            "type": practicetest.difficult_type,
            "description": practicetest.explanation,
          })
        }
      })

      this.spinner.show();
      await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        if (err) {
          await this.spinner.hide();

          this.router.navigate(['/login']);
        }
        else {
          var token = '';
          await this.service.bulkuploded(sheet, "Practiceque", token).then(data => {
            var list = JSON.parse(<string>data[0].json);
            if (data[0].status == 200) {
              Swal.fire(
                list.data.length,
                'Questions added successfully.',
                'success'
              )
              this.listPracticalQues();
              this.closeBulkUploadModal();
              this.spinner.hide();
            }
            else {
              this.service.ShowError(data[0].message)
              this.service.ShowError(list.message)
              this.spinner.hide();
            }
          }, error => {
            console.log(error);
            this.spinner.hide();
          })
        }
      });
    }
    reader.readAsBinaryString(file);
  }
  onRemove(event) {
    this.files.splice(this.files.indexOf(event), 1);
    this.selectBulkupload = true;
    this.selectprogress = false;
  }
  onSelect(event) {
    let me = this;
    var timeleft = 10;
    me.progress = 0;
    me.selectprogress = true;
    me.selectBulkupload = true;
    this.files.push(event.addedFiles);
    var downloadTimer = setInterval(function () {
      if (timeleft <= 0) {
        me.progress = 10 - timeleft;
        me.myEvent = event
        me.selectBulkupload = false;
        me.selectprogress = false;
        clearInterval(downloadTimer);
      }
      me.progress = 10 - timeleft;
      timeleft -= 1;
    }, 200);
  }

  ExportExcel() {
    var certification = Object.assign(this.Certificates.map(k => ({ name: k.certificate_name })));
    var domain = Object.assign(this.Domain.map(k => ({ name: k.domin_name })));
    var subdomain = Object.assign(this.SubDomain.map(k => ({ name: k.subdomain_name })));
    var topic = Object.assign(this.Topic.map(k => ({ name: k.topic_name })));
    var Exam = Object.assign(this.testdata.map(k => ({ name: k.practice_name })));
    var Correct = [{ workSheet: "Correct", rows: [{ name: "1" }, { name: "2" }, { name: "3" }, { name: "4" }], properties: { state: 'hidden' } }]
    var Type = [{ workSheet: "Type", rows: [{ name: "VERY SIMPLE" }, { name: "SIMPLE" }, { name: "AVERAGE" }, { name: "ABOVE AVERAGE" }, { name: "HARD" }, { name: "DIFFICULT" }, , { name: "TRICKY" }], properties: { state: 'hidden' } }]
    var certificationData = [
      {
        workSheet: "certification",
        rows: certification,
        properties:
          { state: 'hidden' }
      }
    ];
    var domainData = [
      {
        workSheet: "domain",
        rows: domain,
        properties:
          { state: 'hidden' }
      }
    ];
    var subdomainData = [
      {
        workSheet: "subdomain",
        rows: subdomain,
        properties:
          { state: 'hidden' }
      }
    ];
    var topicData = [
      {
        workSheet: "topic",
        rows: topic,
        properties:
          { state: 'hidden' }
      }
    ];
    var ExamData = [
      {
        workSheet: "Exam",
        rows: Exam,
        properties:
          { state: 'hidden' }
      }
    ];
    var PracticeQuestion_sample = [
      {
        name: "PracticeQuestion_sample",
        values: [{ header: "certification", value: [{ name: "certification!$A$2:$A$" + (certification.length + 1) }] },
        { header: "domain", value: [{ name: "domain!$A$2:$A$" + (domain.length + 1) }] },
        { header: "subdomain", value: [{ name: "subdomain!$A$2:$A$" + (subdomain.length + 1) }] },
        { header: "topic", value: [{ name: "topic!$A$2:$A$" + (topic.length + 1) }] },
        { header: "Exam", value: [{ name: "Exam!$A$2:$A$" + (Exam.length + 1) }] },
        { header: "question", value: "" },
        { header: "answer_a", value: "" },
        { header: "answer_b", value: "" },
        { header: "answer_c", value: "" },
        { header: "answer_d", value: "" },
        { header: "correct_answer", value: [{ name: "Correct!$A$2:$A$5" }] },
        { header: "difficult_type", value: [{ name: "Type!$A$2:$A$8" }] },
        { header: "explanation", value: "" }
        ],
        properties: { state: "visible" }
      }
    ];
    var workbookData = [this.transform(PracticeQuestion_sample)[0], certificationData[0], domainData[0], subdomainData[0], topicData[0], ExamData[0], Correct[0], Type[0]]
    this.excelService.exportAsExcelFile(workbookData, PracticeQuestion_sample[0].name);
  }
  transform(data) {
    const noOfRowaToGenerate = 5;
    return data.map(({ name, values, properties }) => {
      const headers = values.reduce((prev, next) =>
      ({
        ...prev, [next.header]: Array.isArray
          (next.value) ? next.value.map(({ name }) => name) : next.value
      }), {})
      return {
        workSheet: name,
        rows: Array(noOfRowaToGenerate).fill(headers),
        properties: properties
      }
    })
  }
}
export interface courselist {
  srno: number;
  id: string;
  test_id: string;
  title: string;
  first_choice: string;
  second_choice: string;
  third_choice: string;
  fourth_choice: string;
  answer: string;
  type: string;
  d_id: string;
  sd_id: string;
  point: string;
  topic_id: string;
  ref_link: string;
  youtube_link: string;
  bookpage_no: string;
  blog_url: string;
  createdAt: string;
  updatedAt: string;
  domin_name: string;
  subdomain_name: string;
  topic_name: string;
  practice_name: string;
  description: string;
  certi_id: string;
  certificate_name: string;
}
