// bar-chart.component.ts
import {
    IBarChartOptions,
    IChartistAnimationOptions,
    IChartistData
} from 'chartist';
import { ChartEvent, ChartType } from 'ng-chartist';

import { Component } from '@angular/core';
import { UserService } from "../../shared/user.service";
import { Router } from "@angular/router";
import { P } from '@angular/core/src/render3';


@Component({
    selector: 'app-bar-chart',
    template: `
        <h4 style="color:#477ac5">Top 8 Query Searches</h4>
        <x-chartist
        [type]="type"
        [data]="data"
        [options]="options"
        [events]="events"
        ></x-chartist>
    `
})
export class BarChartComponent {
    sortBy = { sortBy: "query_searches"};
    userDetails;
    globalProperties;
    labels = [];
    series = [[]];
    data: IChartistData;

    filtersLoaded: Promise<boolean>;

    constructor(private userService: UserService, private router: Router) {}

    ngOnInit() {
        this.sortBy = { sortBy: "query_searches"};
    
        this.userService.getUserProfile().subscribe(
          res => {
            this.userDetails = res["user"];
          },
          err => {}
        );
        this.userService.getAllGlobalProperties(this.sortBy).subscribe(
          res => {
            this.globalProperties = res["globalProperties"];
            if(this.globalProperties.length < 8) {
                for(var i = 0; i < this.globalProperties.length; i++) {
                    this.series[0][i] = this.globalProperties[i].query_searches;
                    this.labels[i] = this.globalProperties[i].search_query;
                }  
            } else {
                for(var i = 0; i < 8; i++) {
                    this.series[0][i] = this.globalProperties[i].query_searches;
                    this.labels[i] = this.globalProperties[i].search_query;
                }
            }

            this.data = {
                labels: this.labels,
                series: this.series
            };

            // this.globalProperties = JSON.parse(this.globalProperties);
            this.filtersLoaded = Promise.resolve(true); // Setting the Promise as resolved
          },
          err => {}
        );
      }
    
    type: ChartType = 'Bar';

    // data: IChartistData = {
    //     labels: this.labels,
    //     series: this.series
    // };

options: IBarChartOptions = {
    axisX: {
    showGrid: false
    },
    height: 300,
    width: 600,
};

events: ChartEvent = {
    draw: (data) => {
    if (data.type === 'bar') {
        data.element.animate({
        y2: <IChartistAnimationOptions>{
            dur: '0.5s',
            from: data.y1,
            to: data.y2,
            easing: 'easeOutQuad'
        }
        });
    }
    }
};
}