import { Component, OnInit } from '@angular/core';
import { AuthserviceService } from '../../authservice.service';
import { ServicesService } from '../../services.service';
import { SearchserviceService } from '../../services/search/searchservice.service';

import { NgxSpinnerService } from 'ngx-spinner';
import { Router } from '@angular/router';
@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.scss'],
})
export class SearchComponent implements OnInit {
  Search: any;
  FlashCard = [];
  FlashCardFilter = [];
  Videos = [];
  MindMaps = [];
  MindMapsFilter = [];
  VideosFilter = [];
  Practice = [];
  PracticeFilter = [];
  Studymaterial = [];
  Ppt = [];
  PptFilter = [];
  SearchData = {
    FlashCards: [
      {
        id: 106,
        free_paid: 'free',
        d_id: 12,
        sd_id: 37,
        certi_id: 1,
        cource_id: 1,
        topic_id: 28,
        term: 'test',
        definition: 'test2',
        ref_link: '',
        youtube_link: '',
        bookpage_no: '',
        blog_url: '',
        status: 0,
        createdAt: '2020-10-21T13:25:05.000Z',
        updatedAt: '2020-10-21T13:25:05.000Z',
        domain: {
          id: 12,
          domin_name: 'Security Architecture and Engineering',
        },
        subdomain: {
          id: 37,
          subdomain_name:
            '4.1 Implement secure design principles in network architectures',
        },
        topic: {
          id: 28,
          topic_name: 'Collection limitation',
        },
        certificate: {
          id: 1,
          certificate_name: 'Cissp',
        },
        cource: {
          id: 1,
          course_name: 'Certified Cloud Security Professional',
        },
      },
      {
        id: 106,
        free_paid: 'free',
        d_id: 12,
        sd_id: 37,
        certi_id: 1,
        cource_id: 1,
        topic_id: 28,
        term: 'this is flash',
        definition: 'another flash',
        ref_link: '',
        youtube_link: '',
        bookpage_no: '',
        blog_url: '',
        status: 0,
        createdAt: '2020-10-21T13:25:05.000Z',
        updatedAt: '2020-10-21T13:25:05.000Z',
        domain: {
          id: 12,
          domin_name: 'X',
        },
        subdomain: {
          id: 37,
          subdomain_name: '123456',
        },
        topic: {
          id: 28,
          topic_name: 'Collection limitation',
        },
        certificate: {
          id: 1,
          certificate_name: 'Cissp',
        },
        cource: {
          id: 1,
          course_name: 'Certified Cloud Security Professional',
        },
      },
    ],
    Videos: [
      {
        subtopic_ids: ['4'],
        viewed_users: [],
        id: 3,
        video_link: 'http://static.videogular.com/assets/videos/videogular.mp4',
        video_title: 'My Video',
        video_thumbnil:
          'https://cisspuploads.s3.us-east-2.amazonaws.com/bc195bfd-a659-4cad-90ec-30b21b803a68.png',
        c_id: 1,
        d_id: 11,
        sd_id: 25,
        topic_id: 25,
        type: 'FREE',
        video_type: 'REQUIRED',
        transcript_link:
          'https://cisspuploads.s3.us-east-2.amazonaws.com/3980cdb2-f68c-44f1-9301-aed77fb3619b.txt',
        status: 0,
        createdAt: '2020-11-05T08:17:57.000Z',
        updatedAt: '2020-11-05T08:17:57.000Z',
        domain: {
          id: 11,
          domin_name: '   Security Architecture and Engineering',
        },
        subdomain: {
          id: 25,
          subdomain_name:
            '3.1 Implement and manage engineering processes usi...',
        },
        cource: {
          id: 1,
          course_name: 'Certified Cloud Security Professional',
          short_name: 'ccsp',
        },
        topic: {
          id: 25,
          topic_name: 'Data classification policy',
        },
      },
      {
        subtopic_ids: ['4'],
        viewed_users: [],
        id: 4,
        video_link: 'http://static.videogular.com/assets/videos/videogular.mp4',
        video_title: 'title sample',
        video_thumbnil:
          'https://cisspuploads.s3.us-east-2.amazonaws.com/df3c3d6d-661f-4b87-a9c4-819952b2f4f6.png',
        c_id: 1,
        d_id: 11,
        sd_id: 25,
        topic_id: 25,
        type: 'FREE',
        video_type: 'REQUIRED',
        transcript_link:
          'https://cisspuploads.s3.us-east-2.amazonaws.com/011aac92-c87d-495f-b9b0-054d8a7ea016.txt',
        status: 0,
        createdAt: '2020-11-06T06:24:38.000Z',
        updatedAt: '2020-11-06T06:24:38.000Z',
        domain: {
          id: 11,
          domin_name: '   Security Architecture and Engineering',
        },
        subdomain: {
          id: 25,
          subdomain_name:
            '3.1 Implement and manage engineering processes usi...',
        },
        cource: {
          id: 1,
          course_name: 'Certified Cloud Security Professional',
          short_name: 'ccsp',
        },
        topic: {
          id: 25,
          topic_name: 'Data classification policy',
        },
      },
      {
        subtopic_ids: ['5'],
        viewed_users: [],
        id: 5,
        video_link: 'http://static.videogular.com/assets/videos/videogular.mp4',
        video_title: 'my new video',
        video_thumbnil:
          'https://cisspuploads.s3.us-east-2.amazonaws.com/a58c9402-d9f5-4e53-839a-5037b96f3d9d.png',
        c_id: 1,
        d_id: 11,
        sd_id: 25,
        topic_id: 25,
        type: 'FREE',
        video_type: 'REQUIRED',
        transcript_link:
          'https://cisspuploads.s3.us-east-2.amazonaws.com/2e9c21cc-55bd-4893-b51b-1a5054ddf8a8.txt',
        status: 0,
        createdAt: '2020-11-06T09:11:37.000Z',
        updatedAt: '2020-11-06T09:11:37.000Z',
        domain: {
          id: 11,
          domin_name: '   Security Architecture and Engineering',
        },
        subdomain: {
          id: 25,
          subdomain_name:
            '3.1 Implement and manage engineering processes usi...',
        },
        cource: {
          id: 1,
          course_name: 'Certified Cloud Security Professional',
          short_name: 'ccsp',
        },
        topic: {
          id: 25,
          topic_name: 'Data classification policy',
        },
      },
      {
        subtopic_ids: ['6'],
        viewed_users: [],
        id: 6,
        video_link: 'http://static.videogular.com/assets/videos/videogular.mp4',
        video_title: 'title',
        video_thumbnil:
          'https://cisspuploads.s3.us-east-2.amazonaws.com/de201270-1148-4443-86d2-b7282343fa3c.png',
        c_id: 1,
        d_id: 14,
        sd_id: 45,
        topic_id: 35,
        type: 'FREE',
        video_type: 'REQUIRED',
        transcript_link:
          'https://cisspuploads.s3.us-east-2.amazonaws.com/b036f313-cb04-45c0-a7ed-b0368de3cf3a.txt',
        status: 0,
        createdAt: '2020-11-06T09:17:23.000Z',
        updatedAt: '2020-11-06T09:17:23.000Z',
        domain: {
          id: 14,
          domin_name: ' Security Assessment and Testing',
        },
        subdomain: {
          id: 45,
          subdomain_name:
            '6.1 Design and validate assessment, test, and audit strategies',
        },
        cource: {
          id: 1,
          course_name: 'Certified Cloud Security Professional',
          short_name: 'ccsp',
        },
        topic: {
          id: 35,
          topic_name: 'Crypto shredding',
        },
      },
    ],
    PracticeQuestions: [
      {
        id: 1,
        test_id: 1,
        title: 'test234',
        first_choice: '2',
        second_choice: '1',
        third_choice: '4',
        fourth_choice: '3',
        answer: 1,
        type: 'VERY SIMPLE',
        d_id: 1,
        sd_id: 1,
        topic_id: 1,
        subtopic_id: null,
        ref_link: 'reflink.com',
        youtube_link: 'youtubelink.com',
        bookpage_no: '2',
        blog_url: 'blogurl.com',
        description: null,
        status: 0,
        createdAt: '2020-09-05T17:37:48.000Z',
        updatedAt: '2020-09-07T10:08:59.000Z',
        domain: {
          id: 1,
          domin_name: 'Security and Risk Management ',
        },
        subdomain: {
          id: 1,
          subdomain_name:
            'The confidentiality, integrity and availability of information;',
        },
        topic: {
          id: 1,
          topic_name:
            'Implement secure communication channels according to design',
        },
        practicetest: {
          id: 1,
          practice_name: 'CISSP Practice Test -1',
        },
      },
      {
        id: 2,
        test_id: 1,
        title:
          'll of Testbook and more in the palm of your hands! Practice thousands of questions for free while having fun! Take free quizzes',
        first_choice: '1',
        second_choice: '2',
        third_choice: '3',
        fourth_choice: '4',
        answer: 2,
        type: 'VERY SIMPLE',
        d_id: 11,
        sd_id: 2,
        topic_id: 3,
        subtopic_id: null,
        ref_link: 'reflink.com',
        youtube_link: 'youtubelink.com',
        bookpage_no: '2',
        blog_url: 'blogurl.com',
        description: null,
        status: 0,
        createdAt: '2020-09-05T18:05:36.000Z',
        updatedAt: '2020-10-08T10:45:11.000Z',
        domain: {
          id: 11,
          domin_name: '   Security Architecture and Engineering',
        },
        subdomain: {
          id: 2,
          subdomain_name: 'Security governance principles;',
        },
        topic: {
          id: 3,
          topic_name: 'A candidate that doesn’t have the',
        },
        practicetest: {
          id: 1,
          practice_name: 'CISSP Practice Test -1',
        },
      },
      {
        id: 3,
        test_id: 2,
        title: 'test-3',
        first_choice: '3',
        second_choice: '2',
        third_choice: '4',
        fourth_choice: '1',
        answer: 4,
        type: 'VERY SIMPLE',
        d_id: 1,
        sd_id: 1,
        topic_id: 1,
        subtopic_id: null,
        ref_link: 'reflink.com',
        youtube_link: 'youtubelink.com',
        bookpage_no: '2',
        blog_url: 'blogurl.com',
        description: null,
        status: 0,
        createdAt: '2020-09-05T18:41:00.000Z',
        updatedAt: '2020-09-07T10:09:13.000Z',
        domain: {
          id: 1,
          domin_name: 'Security and Risk Management ',
        },
        subdomain: {
          id: 1,
          subdomain_name:
            'The confidentiality, integrity and availability of information;',
        },
        topic: {
          id: 1,
          topic_name:
            'Implement secure communication channels according to design',
        },
        practicetest: {
          id: 2,
          practice_name: 'cissp test-2',
        },
      },
      {
        id: 4,
        test_id: 1,
        title:
          "Which one of the following refers to a series of characters used to verify a user's identity?",
        first_choice: 'Token serial number',
        second_choice: 'UserID',
        third_choice: 'Password',
        fourth_choice: 'Security Ticket',
        answer: 3,
        type: 'AVERAGE',
        d_id: 9,
        sd_id: 7,
        topic_id: 7,
        subtopic_id: null,
        ref_link: '',
        youtube_link: '',
        bookpage_no: '',
        blog_url: '',
        description: null,
        status: 0,
        createdAt: '2020-09-07T10:14:53.000Z',
        updatedAt: '2020-09-07T10:14:53.000Z',
        domain: {
          id: 9,
          domin_name: 'Security and Risk Management',
        },
        subdomain: {
          id: 7,
          subdomain_name: '1.1 Confidentiality, integrity, and availability',
        },
        topic: {
          id: 7,
          topic_name: 'Integrity',
        },
        practicetest: {
          id: 1,
          practice_name: 'CISSP Practice Test -1',
        },
      },
      {
        id: 5,
        test_id: 1,
        title:
          'When securing Internet connections, which one of the following should be used to protect internal routing and labeling schemes?',
        first_choice: 'Virtual Private Networks (VPN)',
        second_choice: 'Layer 2 Tunneling Protocol (L2TP)',
        third_choice: 'Domain Name Systems (DNS)',
        fourth_choice: 'Network Address Translation (NAT)',
        answer: 4,
        type: 'ABOVE AVERAGE',
        d_id: 9,
        sd_id: 7,
        topic_id: 5,
        subtopic_id: null,
        ref_link: '',
        youtube_link: '',
        bookpage_no: '',
        blog_url: '',
        description: null,
        status: 0,
        createdAt: '2020-09-07T10:16:16.000Z',
        updatedAt: '2020-09-07T10:16:16.000Z',
        domain: {
          id: 9,
          domin_name: 'Security and Risk Management',
        },
        subdomain: {
          id: 7,
          subdomain_name: '1.1 Confidentiality, integrity, and availability',
        },
        topic: {
          id: 5,
          topic_name: 'Goals of Information Security',
        },
        practicetest: {
          id: 1,
          practice_name: 'CISSP Practice Test -1',
        },
      },
    ],
    MindMaps: {},
  };
  PdfPptset: any;
  Pptset: any;
  Xlsset: any;
  Imgset: any;
  showPdfPpt: boolean = false;
  showImg: boolean = false;
  showXls: boolean = false;

  constructor(
    public router: Router,
    public auth: AuthserviceService,
    public service: ServicesService,
    public spinner: NgxSpinnerService,
    public SearchserviceService: SearchserviceService
  ) {
    this.service.headershow = true;
    this.service.SearchValue = true;
    var access = window.localStorage.getItem('accessitem');
    var setlogin = this.auth.isLoggedIn();
    if (!setlogin) {
      this.router.navigate(['/login']);
      this.spinner.hide();
    }
    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;
      }
    }
    this.service.title = '';
    this.service.headerset = {
      dashboard: false,
      studyguuide: false,
      knowledge: false,
      practice: false,
      cat: false,
      datestring: false,
      CATresult: false,
      CATQue: false,
      PracticeResult: false,
      Practiceques: false,
      knowques: false,
      knowresult: false,
      studentprofile: false,
      resource: false,
      liveSupport: false
    };
  }
  Videoclick(vid) {
    var data = btoa(JSON.stringify(vid.id));
    this.router.navigate([`/videolesson/${data}`]);
  }
  MindMapClick(mind) {
    var data = btoa(JSON.stringify(mind.id));
    this.router.navigate([`/mindmaps/${data}`]);
  }

  async ngOnInit() {
    await this.getSearchData();
    let me = this;
    var el = document.getElementById('HeaderSearch') as HTMLInputElement;
    if (el) {
      el.addEventListener('keyup', function () {
        const inputElement: HTMLInputElement = document.getElementById(
          'HeaderSearch'
        ) as HTMLInputElement;
        me.Search = inputElement.value;
        me.searchFilter();
      });
    }
  }
  async getSearchData() {
    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
        this.spinner.show();
        await this.SearchserviceService.getSearchData(token).then(
          async (data) => {
            if (data[0].status == 200) {
              var list = JSON.parse(<string>data[0].json);
              console.log(list.data)
              this.SearchData = list.data;
              const pdfFiles = [];
              const pptFiles = [];
              const imageFiles = [];
              const excelFiles = [];
              this.SearchData[0].Study.forEach(item => {
                if (item.pdf_files) {
                  pdfFiles.push(...JSON.parse(item.pdf_files));
                }
                if (item.ppt_files) {
                  pptFiles.push(...JSON.parse(item.ppt_files));
                }
                if (item.image_files) {
                  imageFiles.push(...JSON.parse(item.image_files));
                }
                if (item.excel_files) {
                  excelFiles.push(...JSON.parse(item.excel_files));
                }
              });
              this.FlashCard = pdfFiles;
              this.Videos = this.SearchData[0].Videos;
              this.MindMaps = excelFiles;
              this.Practice = imageFiles;
              this.Ppt = pptFiles
              // this.FlashCard = this.SearchData[0].FlashCards;
              // this.Videos = this.SearchData[0].Videos;
              // this.MindMaps = this.SearchData[0].MindMaps;
              // this.Practice = this.SearchData[0].PracticeQuestions;
            }
          }
        );
        this.spinner.hide();
      }
    });
  }
  onDocumentLoaded(){
    this.spinner.hide();
  }
  onPdfPptopen(Url, item, file){
    this.spinner.show();
    if(file == 'PDF'){
      this.PdfPptset = Url;
      this.showPdfPpt = true;
    }else if(file == 'PPT'){
      this.PdfPptset = Url;
      this.showPdfPpt = true;
    }
  }
  onExcelOpen(xlsUrl, item){
    this.spinner.show();
    this.Xlsset = xlsUrl;
    this.showXls = true;
  }
  onImgOpen(imgUrl, item){
    this.Imgset = imgUrl;
    this.showImg = true;
  }
  searchFilter() {
    if (this.Search == '' || this.Search == null || this.Search == undefined) {
      this.FlashCardFilter = [];
      this.VideosFilter = [];
      this.PracticeFilter = [];
      this.Studymaterial = [];
      this.MindMapsFilter = [];
      this.PptFilter = [];
    } else {
      let me = this;
      this.FlashCardFilter = this.FlashCard.filter(function (x) {
        if (
          (x.PdfTitle ? x.PdfTitle : '')
            .toLowerCase()
            .includes(me.Search.toLowerCase()) || 
          (x.title ? x.title : '')
            .toLowerCase()
            .includes(me.Search.toLowerCase())
        ) {
          return true;
        }
      });
      this.PptFilter = this.Ppt.filter(function (x) {
        if (
          (x.PptTitle ? x.PptTitle : '')
            .toLowerCase()
            .includes(me.Search.toLowerCase()) || 
          (x.title ? x.title : '')
            .toLowerCase()
            .includes(me.Search.toLowerCase())
        ) {
          debugger;
          return true;
        }
      });
      // this.FlashCardFilter = this.FlashCard.filter(function (x) {
      //   if (
      //     (x.domain.domin_name ? x.domain.domin_name : '')
      //       .toLowerCase()
      //       .includes(me.Search.toLowerCase()) ||
      //     (x.subdomain.subdomain_name ? x.subdomain.subdomain_name : '')
      //       .toLowerCase()
      //       .includes(me.Search.toLowerCase()) ||
      //     (x.certificate.certificate_name ? x.certificate.certificate_name : '')
      //       .toLowerCase()
      //       .includes(me.Search.toLowerCase()) ||
      //     (x.topic ? x.topic.topic_name : '')
      //       .toLowerCase()
      //       .includes(me.Search.toLowerCase()) ||
      //     (x.term ? x.term : '')
      //       .toLowerCase()
      //       .includes(me.Search.toLowerCase()) ||
      //     (x.definition ? x.definition : '')
      //       .toLowerCase()
      //       .includes(me.Search.toLowerCase())
      //   ) {
      //     return true;
      //   }
      // });
      this.VideosFilter = this.Videos.filter(function (x) {
        let filter_topicName = x.topics?.filter(item => item.topic_name.toLowerCase() == me.Search.toLowerCase());
        if (
          (x.domain.domin_name ? x.domain.domin_name : '')
            .toLowerCase()
            .includes(me.Search.toLowerCase()) ||
          (x.subdomain[0].subdomain_name ? x.subdomain[0].subdomain_name : '')
            .toLowerCase()
            .includes(me.Search.toLowerCase()) ||
          (filter_topicName && filter_topicName.length > 0 ? filter_topicName[0].topic_name : '')
            .toLowerCase()
            .includes(me.Search.toLowerCase()) ||
          (x.video_title ? x.video_title : '')
            .toLowerCase()
            .includes(me.Search.toLowerCase())
        ) {
          return true;
        }
      })
      this.MindMapsFilter = this.MindMaps.filter(function (x) {
        if (
          (x.ExcelTitle ? x.ExcelTitle : '')
            .toLowerCase()
            .includes(me.Search.toLowerCase()) || 
          (x.title ? x.title : '')
            .toLowerCase()
            .includes(me.Search.toLowerCase())
        ) {
          return true;
        }
      });
      // this.MindMapsFilter = this.MindMaps.filter(function (x) {
      //   if (
      //     (x.domain.domin_name ? x.domain.domin_name : '')
      //       .toLowerCase()
      //       .includes(me.Search.toLowerCase()) ||
      //     (x.subdomain.subdomain_name ? x.subdomain.subdomain_name : '')
      //       .toLowerCase()
      //       .includes(me.Search.toLowerCase()) ||
      //     (x.certificate.certificate_name ? x.certificate.certificate_name : '')
      //       .toLowerCase()
      //       .includes(me.Search.toLowerCase()) ||
      //     (x.name ? x.name : '').toLowerCase().includes(me.Search.toLowerCase())
      //   ) {
      //     return true;
      //   }
      // });
      this.PracticeFilter = this.Practice.filter(function (x) {
        if (
          (x.ImgTitle ? x.ImgTitle : '')
            .toLowerCase()
            .includes(me.Search.toLowerCase()) || 
          (x.title ? x.title : '')
            .toLowerCase()
            .includes(me.Search.toLowerCase())
        ) {
          return true;
        }
      });
      // this.PracticeFilter = this.Practice.filter(function (x) {
      //   if (
      //     (x.domain.domin_name ? x.domain.domin_name : '')
      //       .toLowerCase()
      //       .includes(me.Search.toLowerCase()) ||
      //     (x.subdomain.subdomain_name ? x.subdomain.subdomain_name : '')
      //       .toLowerCase()
      //       .includes(me.Search.toLowerCase()) ||
      //     (x.topic ? x.topic.topic_name : '')
      //       .toLowerCase()
      //       .includes(me.Search.toLowerCase()) ||
      //     (x.practicetest.practice_name ? x.practicetest.practice_name : '')
      //       .toLowerCase()
      //       .includes(me.Search.toLowerCase()) ||
      //     (x.title ? x.title : '')
      //       .toLowerCase()
      //       .includes(me.Search.toLowerCase())
      //   ) {
      //     return true;
      //   }
      // });

      // this.Studymaterial = this.SearchData[0].Study.filter(x =>
      //   x.title.toLowerCase().includes(me.Search.toLowerCase()) ||
      //   x.content.toLowerCase().includes(me.Search.toLowerCase())
      // )
    }

  }
  retuey() {
    window.location.reload();
  }
}
