import { Component, OnInit } from '@angular/core';
import {PastYearMonthlyData} from '../models/PastYearMonthly.model';
import {Observable} from 'rxjs';
import {HttpClient} from '@angular/common/http';
import {AuthService} from '../service/auth.service';
import {map} from 'rxjs/operators';

@Component({
  selector: 'app-chart-past-year-monthly-performance',
  templateUrl: './chart-past-year-monthly-performance.component.html',
  styleUrls: ['./chart-past-year-monthly-performance.component.scss']
})
export class ChartPastYearMonthlyPerformanceComponent implements OnInit {
  pastYearData: Observable<PastYearMonthlyData[]>;

  constructor(private http: HttpClient, private auth: AuthService) { }

  ngOnInit(): void {
    this.pastYearData = this.getPastYearMonthly();
  }

  // tslint:disable-next-line:typedef
  private getPastYearMonthly(): Observable<PastYearMonthlyData[]> {
    return this.http.get<PastYearMonthlyData[]>(this.auth.getUrl('chart/past-year-monthly')).pipe(map(
      data => {
        let ret = [];
        data.forEach( (value: PastYearMonthlyData , index: number ) => {
          let a = {
            Period: value.Period,
            Amount: value.Amount / 1000,
            Summary: '',
          };
          if (index > 0) {
            a.Amount -= (data[index - 1].Amount / 1000);
          }
          ret.push(a);
        });
        return ret;
      }
    ));
  }

  public pointColor(point: any): string {
    const summary = point.dataItem.summary;
    if (summary) {
      return summary === 'total' ? '#555' : 'gray';
    }

    if (point.value > 0) {
      return 'green';
    } else {
      return 'lightyellow';
    }
  }
}
