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 { Router } from '@angular/router';
import { ServicesService } from '../../services.service';
import { NgxSpinnerService } from "ngx-spinner";
import { MatSort } from '@angular/material/sort';
import { AuthorizationService } from '../../service/authorization.service';
import { FormBuilder, FormGroup, Validators, FormArray, FormControl } from '@angular/forms';
import { CertificateService } from '../../services/certificate/certificate.service';
import * as ClassicEditor from '@blowstack/ckeditor5-full-free-build';
import { SelfpacedService } from 'src/app/services/selfpaced/selfpaced.service';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
@Component({
  selector: 'app-certificate',
  templateUrl: './certificate.component.html',
  styleUrls: ['./certificate.component.scss']
})
export class CertificateComponent implements OnInit {
  displayedColumns: string[] = ['srno', 'certificate_name', 'actions'];
  dataSource: MatTableDataSource<certificatelist>;
  Search: any;
  addNew: boolean = false;
  CertificateName: any;
  CourseShort: any;
  id: any;
  EditHideen = true;
  download_url: any;
  loglist = [];
  IsUpdate: boolean = true;
  @Input('pagination') pagination: boolean;
  @ViewChild(MatPaginator, { static: false }) set matPaginator(paginator: MatPaginator) {
    if (this.pagination) {
      this.dataSource.paginator = paginator;
    }
  }
  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
  @ViewChild(MatSort, { static: true }) sort: MatSort;
  public Editor = ClassicEditor;
  public CourseForm: FormGroup;
  live_course_thumbnail: any;
  live_welcome_thumbnail: any;
  live_welcome_video: any;
  self_course_thumbnail: any;
  self_welcome_thumbnail: any;
  self_welcome_video: any;
  hybrid_course_thumbnail: any;
  hybrid_welcome_thumbnail: any;
  hybrid_welcome_video: any;
  Domains = [];
  changeDomain = [];
  oldAuditValueArray = {
    "Name": "", "Sort Name": "", "Live course thumbnail": "", "Live welcome thumbnail": "", "Live welcome video": "", "Self course thumbnail": "", "Self welcome thumbnail": "", "Self welcome video": "", "Hybrid course thumbnail": "", "Hybrid welcome thumbnail": "", "Hybrid welcome video": ""
  }
  newAuditValueArray = {
    "Name": "", "Sort Name": "", "Live course thumbnail": "", "Live welcome thumbnail": "", "Live welcome video": "", "Self course thumbnail": "", "Self welcome thumbnail": "", "Self welcome video": "", "Hybrid course thumbnail": "", "Hybrid welcome thumbnail": "", "Hybrid welcome video": ""
  }
  auditHistory = "";
  constructor(public certificateService: CertificateService, public fb: FormBuilder, public auth: AuthorizationService, public router: Router, public spinner: NgxSpinnerService, public service: ServicesService, public sefpaceService: SelfpacedService) {
    var setlogin = this.auth.isLoggedIn();
    if (!setlogin) {
      this.router.navigate(['/login']);
    }
    this.CourseForm = this.fb.group({
      CertificateName: ['', Validators.required],
      CourseShort: ['', Validators.required],
      live_course_thumbnail: new FormControl(),
      live_welcome_thumbnail: new FormControl(),
      live_welcome_video: new FormControl(),
      self_course_thumbnail: new FormControl(),
      self_welcome_thumbnail: new FormControl(),
      self_welcome_video: new FormControl(),
      hybrid_course_thumbnail: new FormControl(),
      hybrid_welcome_thumbnail: new FormControl(),
      hybrid_welcome_video: new FormControl()
    });
  }
  async ngOnInit() {
    await this.spinner.show();
    await this.listCertificatedata();
    await this.spinner.hide();
  }
  closeModal() {
    this.addNew = false
    this.CertificateName = "";
    this.CourseShort = "";
    this.live_course_thumbnail = "";
    this.live_welcome_thumbnail = "";
    this.live_welcome_video = "";
    this.self_course_thumbnail = "";
    this.self_welcome_thumbnail = "";
    this.self_welcome_video = "";
    this.hybrid_course_thumbnail = "";
    this.hybrid_welcome_thumbnail = "";
    this.hybrid_welcome_video = "";
    this.oldAuditValueArray = {
      "Name": "", "Sort Name": "", "Live course thumbnail": "", "Live welcome thumbnail": "", "Live welcome video": "", "Self course thumbnail": "", "Self welcome thumbnail": "", "Self welcome video": "", "Hybrid course thumbnail": "", "Hybrid welcome thumbnail": "", "Hybrid welcome video": ""
    }
    this.newAuditValueArray = {
      "Name": "", "Sort Name": "", "Live course thumbnail": "", "Live welcome thumbnail": "", "Live welcome video": "", "Self course thumbnail": "", "Self welcome thumbnail": "", "Self welcome video": "", "Hybrid course thumbnail": "", "Hybrid welcome thumbnail": "", "Hybrid welcome video": ""
    }
    this.auditHistory = "";
  }
  async s3Upload() {
    let data = `data:image/jpeg;base64, `;
    await this.auth.uploadFiles(data).then(async (result) => {
    })
  }
  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) => {
      try {
        if (result.value) {
          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.certificateService.Deletecertificate(item.id, token).then(async (value) => {
                if (value[0].status == 200) {
                  var list = JSON.parse(<string>value[0].json);
                  this.auth.getAuthenticatedUser().getSession(async (err, session) => {
                    if (err) {
                      await this.spinner.hide();
                      this.router.navigate(['/login']);
                    }
                    else {
                      var token = ''
                      var e = window.localStorage.getItem("adminUser");
                      if (e == null || e == undefined || e == "") {
                        e = 'admin';
                      }
                      var desc = "certificate is deleted by <span> " + e + "</span>";
                      await this.service.addAdminLogs(desc, "certificate", item.id, token);
                      await this.sefpaceService.deleteSelfPaced(item.id, token);
                    }
                  });
                  await this.listCertificatedata();
                  await this.spinner.hide();
                  Swal.fire(
                    list.message,
                    'Certificate 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();
      }
    })
  }
  async listCertificatedata() {
    try {
      await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        if (err) {
          await this.spinner.hide();
          this.router.navigate(['/login']);
        }
        else {
          var token = ''
          const users: certificatelist[] = [];
          await this.certificateService.ListCertificate(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,
                  "certificate_name": element.certificate_name,
                  "live_course_thumbnail": element.live_course_thumbnail,
                  "live_welcome_thumbnail": element.live_welcome_thumbnail,
                  "live_welcome_video": element.live_welcome_video,
                  "self_course_thumbnail": element.self_course_thumbnail,
                  "self_welcome_thumbnail": element.self_welcome_thumbnail,
                  "self_welcome_video": element.self_welcome_video,
                  "hybrid_course_thumbnail": element.hybrid_course_thumbnail,
                  "hybrid_welcome_thumbnail": element.hybrid_welcome_thumbnail,
                  "hybrid_welcome_video": element.hybrid_welcome_video,
                  "short_name": element.short_name,
                  "domain_sequence": element.domain_sequence
                })
              });
              this.dataSource = new MatTableDataSource(users);
              this.dataSource.sort = this.sort;
              this.dataSource.paginator = this.paginator;
              this.filter();
              this.pagination = true;
            }
          })
        }
      });
    }
    catch (e) {
      this.service.ShowError(e.meassage);
      await this.spinner.hide();
    }
  }
  async filter() {
    this.dataSource.filter = this.Search;
    if (this.pagination) {
      this.dataSource.paginator._changePageSize(this.dataSource.paginator.pageSize);
    }
  }
  openPopup() {
    this.addNew = true;
    this.CertificateName = "";
    this.EditHideen = false;
  }
  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 = ''
        this.service.get_logs("certificate", 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.id = item.id;
    await this.getAllDropDown(item.id);
    this.EditHideen = true;
    this.CertificateName = item.certificate_name;
    this.CourseShort = item.short_name;
    this.live_course_thumbnail = item.live_course_thumbnail;
    this.live_welcome_thumbnail = item.live_welcome_thumbnail;
    this.live_welcome_video = item.live_welcome_video;
    this.self_course_thumbnail = item.self_course_thumbnail;
    this.self_welcome_thumbnail = item.self_welcome_thumbnail;
    this.self_welcome_video = item.self_welcome_video;
    this.hybrid_course_thumbnail = item.hybrid_course_thumbnail;
    this.hybrid_welcome_thumbnail = item.hybrid_welcome_thumbnail;
    this.hybrid_welcome_video = item.hybrid_welcome_video;
    let domain_sequence = item.domain_sequence
    if (domain_sequence) {
      this.Domains = this.Domains.sort((a, b) => {
        return domain_sequence.indexOf(a.id) - domain_sequence.indexOf(b.id);
      });
    }
    this.addNew = true;
    this.oldAuditValueArray = {
      "Name": this.CertificateName, "Sort Name": this.CourseShort, "Live course thumbnail": this.live_course_thumbnail, "Live welcome thumbnail": this.live_welcome_thumbnail, "Live welcome video": this.live_welcome_video, "Self course thumbnail": this.self_course_thumbnail, "Self welcome thumbnail": this.self_welcome_thumbnail, "Self welcome video": this.self_welcome_video, "Hybrid course thumbnail": this.hybrid_course_thumbnail, "Hybrid welcome thumbnail": this.hybrid_welcome_thumbnail, "Hybrid welcome video": this.hybrid_welcome_video
    }
  }
  async getAllDropDown(cert_id) {
    try {
      this.auth.getAuthenticatedUser().getSession(async (err, session) => {
        if (err) {
          await this.spinner.hide();
          this.router.navigate(['/login']);
        }
        else {
          var token = ''
          this.service.token = token;
          await this.service.GetAllDropdown(token).then(async (data) => {
            if (data[0].status == 200) {
              var list = JSON.parse(<string>data[0].json);
              this.Domains = list.data.Domain;
              this.Domains = this.Domains.filter(item => item.certi_id == cert_id);
            }
          })
        }
      })
    }
    catch (e) {
      await this.spinner.hide();
      this.service.ShowError(e.message);
    }
  }
  private swap(array: any[], x: any, y: any) {
    var b = array[x];
    array[x] = array[y];
    array[y] = b;
  }
  moveup(index: any) {
    if (index >= 1) {
      this.swap(this.Domains, index, index - 1);
    }
  }
  movedown(index: any) {
    if (index < this.Domains.length - 1) {
      this.swap(this.Domains, index, index + 1);
    }
  }
  drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(
      this.Domains,
      event.previousIndex,
      event.currentIndex
    );
    this.changeDomain = this.Domains;
  }
  previewFile(event) {
    try {
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
      }
    }
    catch (e) {
    }
  }
  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 onSubmit() {
    this.markFormTouched(this.CourseForm);
    if (this.CourseForm.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 = ''
          await this.certificateService.AddCertificate(this.CertificateName, this.CourseShort, this.live_course_thumbnail, this.live_welcome_thumbnail,
            this.live_welcome_video, this.self_course_thumbnail, this.self_welcome_thumbnail, this.self_welcome_video,
            this.hybrid_course_thumbnail, this.hybrid_welcome_thumbnail, this.hybrid_welcome_video, token).then(async (value) => {
              if (value[0].status == 200) {
                var list = JSON.parse(<string>value[0].json);
                this.auth.getAuthenticatedUser().getSession(async (err, session) => {
                  if (err) {
                    await this.spinner.hide();
                    this.router.navigate(['/login']);
                  }
                  else {
                    var token = ''
                    var e = window.localStorage.getItem("adminUser");
                    if (e == null || e == undefined || e == "") {
                      e = 'admin';
                    }
                    var desc = "Certificate is added by <span> " + e + "</span>";
                    await this.service.addAdminLogs(desc, "certificate", list.data.id, token);
                  }
                });
                await this.listCertificatedata();
                await this.spinner.hide();
                this.service.ShowSuccess("Certificate add successfully");
                this.closeModal();
                this.CertificateName = "";
                this.EditHideen = false;
              }
              else {
                var list = JSON.parse(<string>value[0].json);
                await this.spinner.hide();
                this.service.ShowError(list.message);
              }
            })
        }
      });
    }
  }
  async UpdateCertificate() {
    await this.spinner.show();
    await this.auth.getAuthenticatedUser().getSession(async (err, session) => {
      if (err) {
        await this.spinner.hide();
        this.router.navigate(['/login']);
      }
      else {
        let domain_sequence = this.changeDomain.map((obj) => obj.id);
        var token = ''
        await this.certificateService.UpdateCertificate(this.id, this.CertificateName, this.CourseShort, this.live_course_thumbnail, this.live_welcome_thumbnail,
          this.live_welcome_video, this.self_course_thumbnail, this.self_welcome_thumbnail, this.self_welcome_video,
          this.hybrid_course_thumbnail, this.hybrid_welcome_thumbnail, this.hybrid_welcome_video, domain_sequence, token).then(async (value) => {
            if (value[0].status == 200) {
              var list = JSON.parse(<string>value[0].json);
              this.auth.getAuthenticatedUser().getSession(async (err, session) => {
                if (err) {
                  await this.spinner.hide();
                  this.router.navigate(['/login']);
                }
                else {
                  var token = ''
                  var e = window.localStorage.getItem("adminUser");
                  if (e == null || e == undefined || e == "") {
                    e = 'admin';
                  }
                  this.newAuditValueArray = {
                    "Name": this.CertificateName, "Sort Name": this.CourseShort, "Live course thumbnail": this.live_course_thumbnail, "Live welcome thumbnail": this.live_welcome_thumbnail, "Live welcome video": this.live_welcome_video, "Self course thumbnail": this.self_course_thumbnail, "Self welcome thumbnail": this.self_welcome_thumbnail, "Self welcome video": this.self_welcome_video, "Hybrid course thumbnail": this.hybrid_course_thumbnail, "Hybrid welcome thumbnail": this.hybrid_welcome_thumbnail, "Hybrid welcome video": this.hybrid_welcome_video
                  }
                  var audit = this.auth.compareAuditHist(this.oldAuditValueArray, this.newAuditValueArray);
                  var desc = audit;
                  await this.service.addAdminLogs(desc, "certificate", this.id, token);
                }
              });
              await this.spinner.hide();
              this.service.ShowSuccess(list.message);
              this.closeModal();
              this.listCertificatedata();
            }
            else {
              var list = JSON.parse(<string>value[0].json);
              await this.spinner.hide();
              this.service.ShowError(list.message);
            }
          })
      }
    });
  }
  handleFileSelect(evt) {
    let me = this;
    let file = evt.target.files[0];
    // let mime = "data:" + file.type + ";base64,";
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
      me.uploadFile(file, evt.target.id);
    };
    reader.onerror = function (error) {
      console.log('Error: ', error);
    };
  }
  async uploadFile(image, model) {
    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.sefpaceService.uploadFile(image, token).then(async (imgresponse) => {
          if (imgresponse[0].status == 200) {
            var imglist = JSON.parse(<string>imgresponse[0].json);
            if (model == "live_course_thumbnail")
              this.live_course_thumbnail = "http://64.23.254.43/backend/uploads/"+imglist.data.fileName;
            else if ((model == "live_welcome_thumbnail"))
              this.live_welcome_thumbnail = "http://64.23.254.43/backend/uploads/"+imglist.data.fileName;
            else if ((model == "live_welcome_video"))
              this.live_welcome_video = "http://64.23.254.43/backend/uploads/"+imglist.data.fileName;
            else if ((model == "self_course_thumbnail"))
              this.self_course_thumbnail = "http://64.23.254.43/backend/uploads/"+imglist.data.fileName;
            else if ((model == "self_welcome_thumbnail"))
              this.self_welcome_thumbnail = "http://64.23.254.43/backend/uploads/"+imglist.data.fileName;
            else if ((model == "self_welcome_video"))
              this.self_welcome_video = "http://64.23.254.43/backend/uploads/"+imglist.data.fileName;
            else if ((model == "hybrid_course_thumbnail"))
              this.hybrid_course_thumbnail = imglist.data;
            else if ((model == "hybrid_welcome_thumbnail"))
              this.hybrid_welcome_thumbnail = imglist.data;
            else
              this.hybrid_welcome_video = imglist.data;
            this.spinner.hide();
          } else {
            this.spinner.hide();
          }
        })
      }
    })
  }
}
export interface certificatelist {
  srno: number;
  id: string;
  certificate_name: string;
  short_name: string;
  live_course_thumbnail: string;
  live_welcome_thumbnail: string;
  live_welcome_video: string;
  self_course_thumbnail: string;
  self_welcome_thumbnail: string;
  self_welcome_video: string;
  hybrid_course_thumbnail: string;
  hybrid_welcome_thumbnail: string;
  hybrid_welcome_video: string;
  domain_sequence: string;
}