import {
  Component,
  OnInit,
  Input,
  ViewEncapsulation,
  Output,
  EventEmitter
} from '@angular/core';
import { CallbackModel } from '../../models/callback-model';
import { IPagination } from './ipagination';

@Component({
  selector: 'app-pagination',
  templateUrl: './pagination.component.html',
  styleUrls: ['./pagination.component.scss']
})
export class PaginationComponent {

  @Output() methodToExecute: EventEmitter<IPagination> = new EventEmitter<
    IPagination
  >();

  @Input() totalCount?= 1005;

  @Input() itemsPerPage?= 50;

  @Input() dispPages?= 5;

  pages: number;

  pageArray: any[]

  selectedPage = 1;

  constructor() { }

  ngOnInit() {
    this.pages = Math.ceil(this.totalCount / this.itemsPerPage);
    this.pageArray = this.generateArray(this.pages < this.dispPages ? this.pages : this.dispPages);
  }

  generateArray(no: number): number[] {
    return Array.from(new Array(no), (val, index) => {
      const value = (index + 1);
      //return value.length == 1 ? '0' + value : value;
      return value;
    });
  }

  first() {
    this.selectPage(1);
  }

  previous() {
    const prevPage = this.selectedPage - 1;
    if (prevPage >= 1) {
      this.selectPage(prevPage);
    }
  }

  next() {
    const nextPage = this.selectedPage + 1;
    if (nextPage <= this.pages) {
      this.selectPage(nextPage);
    }
  }

  last() {
    this.selectPage(this.pages);
  }

  reverseLoop(page: number) {
    this.pageArray = [];
    for (let i = page; i > (page - this.dispPages); i--) {
      this.pageArray.unshift(i)
    }
  }

  loop(page: number) {
    this.pageArray = [];
    for (let i = page; i < (page + this.dispPages); i++) {
      this.pageArray.push(i)
    }
  }

  selectPage(page: number) {
    const originalPage = this.selectedPage;
    if (this.pageArray.indexOf(page) == -1) {
      // when selection is out of array, repopulate.
      if (originalPage > page) {
        this.loop(page);
      }
      else {
        this.reverseLoop(page);
      }
    }
    this.selectedPage = page;

    const pagination = {
      positionStart: this.itemsPerPage * (page - 1),
      positionEnd:
        /* if its the last page */
        page == this.pages ? this.totalCount : this.itemsPerPage * page,
      skip: this.itemsPerPage * (page - 1),
      take: this.itemsPerPage,
      pages: this.pages,
      selectedPage: page
    };
    if (page == this.pages) {
      pagination.take = pagination.positionEnd - pagination.positionStart;
    }

    this.PageUpdate(pagination);
  }

  PageUpdate(pagination: IPagination) {
    this.methodToExecute.emit(pagination);
  }
}
