import { Component, OnInit, ViewChild } from '@angular/core';
import { ServicesService } from '../../services.service';
import { NgxSpinnerService } from "ngx-spinner";
import { AuthorizationService } from '../../service/authorization.service';
import { Router } from '@angular/router';
import * as XLSX from 'xlsx';
import { AdminService } from '../../services/admin/admin.service';
import { WebsocketService } from '../../services/websocket/websocket.service';
import { ChartDataSets, ChartOptions } from 'chart.js';
import { Color, Label } from 'ng2-charts';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {
  totalStudent = 0;
  totalTeacher = 0;
  totalClients: number = 0;
  course = 0;
  valueset: any;

  selectedYear: number;
  availableYears: number[];

  constructor(public socket: WebsocketService, public adminService: AdminService, public auth: AuthorizationService, public router: Router, public spinner: NgxSpinnerService, public service: ServicesService) {
    var setlogin = this.auth.isLoggedIn();
    if (!setlogin) {
      this.router.navigate(['/login']);
    }
  }
  async ngOnInit() {
    await this.spinner.show();
    const currentYear = new Date().getFullYear();
    const startingYear = 2024;
    this.selectedYear = currentYear;
    this.availableYears = await this.generateYears(startingYear, currentYear);
    await this.loadDataForYear(this.selectedYear);
    // await this.spinner.hide();
  }
  // line chart for course start
  public lineChartCourseData: ChartDataSets[] = [
    { data: [], label: 'Course' }
  ];
  public lineChartCourseLabels: Label[] = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  public lineChartCourseOptions: ChartOptions = {
    responsive: true
  };
  public lineChartCourseColors: Color[] = [
    {
      borderColor: 'black',
      backgroundColor: '#DF166A'
    }
  ];
  public lineChartCourseLegend = true;
  public lineChartCourseType = 'line';
  public lineChartCoursePlugins = [];
  // line chart end

  // line chart for students start
  public lineChartData: ChartDataSets[] = [
    { data: [], label: 'Students' }
  ];
  public lineChartLabels: Label[] = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  public lineChartOptions: ChartOptions = {
    responsive: true
  };
  public lineChartColors: Color[] = [
    {
      borderColor: 'black',
      backgroundColor: '#DF166A'
    }
  ];
  public lineChartLegend = true;
  public lineChartType = 'line';
  public lineChartPlugins = [];
  // line chart end

  // line chart for Clients start
  public lineChartClientData: ChartDataSets[] = [
    { data: [0, 0, 0, 0, 5], label: 'Clients' }
  ];
  public lineChartClientLabels: Label[] = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  public lineChartClientOptions: ChartOptions = {
    responsive: true
  };
  public lineChartClientColors: Color[] = [
    {
      borderColor: 'black',
      backgroundColor: '#DF166A'
    }
  ];
  public lineChartClientLegend = true;
  public lineChartClientType = 'line';
  public lineChartClientPlugins = [];
  // line chart end

  // line chart for Teachers start
  public lineChartTeacherData: ChartDataSets[] = [
    { data: [], label: 'Teachers' }
  ];
  public lineChartTeacherLabels: Label[] = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  public lineChartTeacherOptions: ChartOptions = {
    responsive: true
  };
  public lineChartTeacherColors: Color[] = [
    {
      borderColor: 'black',
      backgroundColor: '#DF166A'
    }
  ];
  public lineChartTeacherLegend = true;
  public lineChartTeacherType = 'line';
  public lineChartTeacherPlugins = [];
  // line chart end
  async countdash(year) {
    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.adminService.countdash(year, token).then(async (data) => {
          if (data[0].status == 200) {
            var list = JSON.parse(<string>data[0].json)
            await this.pushTotalStudentsData(list.data.TotalStudents);
            await this.pushTotalCourse(list.data.TotalCourse);
            await this.spinner.hide();
          }
        })
      }
    });
  }

  async pushTotalStudentsData(data: { TotalStudents: number, Month: string }[]){
    for (const item of data) {
        this.lineChartData[0].data.push(item.TotalStudents);
    }
  }

  async pushTotalCourse(data: { TotalCourse: number, Month: string }[]){
    for (const item of data) {
        this.lineChartCourseData[0].data.push(item.TotalCourse);
    }
  }

  generateYears(startYear: number, endYear: number): number[] {
    this.spinner.show();
    const years: number[] = [];
    for (let year = endYear; year >= startYear; year--) {
      years.push(year);
    }
    return years;
  }

  onYearChange() {
    this.loadDataForYear(this.selectedYear);
  }

  async loadDataForYear(year: number) {
    await this.countdash(year);
  }

  onFileChange(ev) {
    let workBook = null;
    let jsonData = null;
    const reader = new FileReader();
    const file = ev.target.files[0];
    reader.onload = (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);
    }
    reader.readAsBinaryString(file);
  }
}
