import { Component, OnInit, ViewChild, ViewContainerRef, Input } from '@angular/core';
import { MatPaginator, MatSort } from '@angular/material';
import { ColumnTemplate, DynaDataSource, ConfirmationDialogService, extractRSQL, FieldFilter } from '@xdf/gallery';
import { Pagination, SortField, NotificationType, NotificationService } from '@xdf/commons';
import { Router, ActivatedRoute } from '@angular/router';
import { first, tap } from 'rxjs/operators';
import { TagFilter } from '@xdf/gallery/lib/views/gallery/ngx-tags-input/model/tag-filter';
import { TranslateService } from '@ngx-translate/core';
import { AgentService } from '../../service/agent.service';



const columnTemplateArray = [
  {
    name: 'avatar',
    sortable: true,
    title: 'agent_avatar',
    visible: true,
    filtable: true,
    style: { width: 'auto' },
    type: 'string',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  },
  {
    name: 'id',
    sortable: true,
    title: 'agent_code',
    visible: true,
    filtable: true,
    style: { width: 'auto' },
    type: 'number',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  },
  {
    name: 'name',
    sortable: true,
    title: 'agent_name',
    visible: true,
    filtable: true,
    style: { width: 'auto' },
    type: 'string',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  },
  {
    name: 'version',
    sortable: true,
    title: 'agent_version',
    visible: true,
    filtable: true,
    style: { width: 'auto' },
    type: 'string',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  },
  {
    name: 'status',
    sortable: true,
    title: 'agent_status',
    visible: true,
    filtable: true,
    style: { width: 'auto' },
    type: 'string',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  },
  {
    name: 'countryName',
    sortable: true,
    title: 'agent_country',
    visible: true,
    filtable: true,
    style: { width: 'auto' },
    type: 'string',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  },
  {
    name: 'timezone',
    sortable: true,
    title: 'agent_timezone',
    visible: true,
    filtable: true,
    style: { width: 'auto' },
    type: 'string',
    aliasName: null,
    queryName: null,
    responsive: null,
    styles: null,
    values: null,
    digitsInfo: null,
    dateFormat: null,
    colStyle: null
  }
];


const fieldFilters = [
  new FieldFilter('agent_code', 'id', 'id', 'number', undefined),
  new FieldFilter('agent_name', 'name', 'name', 'string', undefined),
];

@Component({
  selector: 'byte-agent-list',
  templateUrl: './agent-list.component.html',
  styleUrls: ['./agent-list.component.scss']
})
export class AgentListComponent implements OnInit {

  @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;
  @ViewChild(MatSort, { static: false }) sort: MatSort;

  sortColumn: string;
  sortDirection: string;
  statusQuickFilter: string;
  pagingSize = 10;
  programIdentifier = 'agent';

  columnTemplateArray: ColumnTemplate[];
  dataSource: DynaDataSource;
  displayedColumns = new Array<string>();
  fieldFilters: Array<FieldFilter> = fieldFilters;
  filterTags = [];
  pagination: Pagination;
  public resourceAuth: any;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private agentService: AgentService,
    private notificationService: NotificationService,
    private translateService: TranslateService,
    protected confirmationDialogService: ConfirmationDialogService,
    protected vcRef: ViewContainerRef
  ) { }

  ngAfterViewInit(): void {
    this.sort.sortChange.subscribe(() => {
      if (!this.sort.disabled && this.sort.active) {
        this.pagination.sortFields = new Array();
        const sortField: SortField = new SortField();
        sortField.direction = this.sortDirection = this.sort.direction;
        sortField.field = this.sortColumn = this.sort.active;
        this.pagination.sortFields.push(sortField);
      }

      this.paginator.pageIndex = 0;
      this.dataSource.load(this.pagination);
    });

    this.paginator.page
      .pipe(
        tap(() => {
          this.pagination.currentPage = this.paginator.pageIndex;
          this.pagination.itemsPerPage = this.paginator.pageSize;
          this.dataSource.load(this.pagination);
        })
      )
      .subscribe();
  }

  ngOnInit() {
    this.sortColumn = 'id';
    this.sortDirection = 'asc';

    const authList = this.route.snapshot.paramMap['authorization'];

    if (authList) {
      this.resourceAuth = new Object();
      authList.forEach(option => {
        this.resourceAuth[option] = true;
      });
    }

    this.columnTemplateArray = columnTemplateArray;

    this.dataSource = new DynaDataSource(this.agentService);

    const previousState = JSON.parse(localStorage.getItem(this.programIdentifier + '-state'));

    if (previousState) {
      const PAG = 'pagination';
      const FILTERS = 'filtersTags';

      this.pagination = previousState[PAG];
      this.filterTags = previousState[FILTERS];

      localStorage.removeItem(this.programIdentifier + '-state');
    } else {

      // Paginación
      this.pagination = new Pagination();
      this.pagination.currentPage = 0;
      this.pagination.itemsPerPage = this.pagingSize;

      this.pagination.filterExpression = "id != 0";

      // Ordenación por defecto
      if (this.sortColumn && this.sortDirection) {
        this.pagination.sortFields = new Array();
        const sortField: SortField = new SortField();
        sortField.direction = this.sortDirection;
        sortField.field = this.sortColumn;
        this.pagination.sortFields.push(sortField);
      }
    }

    // calculando la columnas a pintar
    this.columnTemplateArray.forEach(column => {
      this.displayedColumns.push(column.name);
    });

    this.displayedColumns.push('actions');

    this.dataSource.load(this.pagination);
  }

  onFilter(tags: Array<TagFilter>) {

    this.filterTags = tags;
    this.pagination.currentPage = 0;

    // let tagsTemp = tags.slice();
    const tagsTemp = tags.map(a => Object.assign({}, a));

    for (let i = 0; i < tagsTemp.length; i++) {
      if (tagsTemp[i].column !== 'id') {
        tagsTemp[i].value = tagsTemp[i].value;
      }
    }

    this.pagination.filterExpression = extractRSQL(tagsTemp);

    if (this.pagination.filterExpression == null || this.pagination.filterExpression == undefined) {
      this.pagination.filterExpression = "id != 0";
    }

    this.dataSource.load(this.pagination);
  }

  onRefresh() {
    this.dataSource.load(this.pagination);
  }

  delete(item) {
    this.confirmationDialogService.loadComponent(
      this.vcRef,
      'title.delete.confirmation',
      'message.delete.confirmation').subscribe(result => {
        if (result) {
          this.agentService.delete(item.id).subscribe((rslt: any) => {

            if (rslt.statusCode != 200) {
              this.notificationService.showMessage(
                this.translateService.instant(rslt.message), this.translateService.instant('label.error.message.title'), NotificationType.error);
            } else {
              this.dataSource.load(this.pagination);
            }

          }

          );
        }
      });
  }

  edit(item) {
    this.router.navigate(['/configuration/agent/detail/edit/' + item.id]);
  }

  synchronize(item) {
    this.agentService.synchronize(item.id).pipe(first()).subscribe(() => {
      this.notificationService.showMessage(this.translateService.instant("agent.synchronize.success"), undefined, NotificationType.success);
      this.onRefresh();
    });
  }

  view(item) {
    this.router.navigate(['/configuration/agent/detail/view/' + item.id]);
  }

  create() {
    this.router.navigate(['/configuration/agent/detail/new']);
  }
}
