import {
  Component,
  OnInit,
  AfterViewInit,
  ElementRef,
  ViewChild
} from '@angular/core';
import * as $ from 'jquery';
import 'datatables.net';
import { Router } from '@angular/router';
import { saveAs } from 'file-saver';
import { AppConfigService } from '../Shared/Common/AppConfigService';
import * as moment from 'moment';
import { DMSAPIService } from '../Shared/Common/DMSAPIService';

@Component({
  selector: 'app-completed-forms-library',
  templateUrl: './completed-forms-library.component.html',
  styleUrls: ['./completed-forms-library.component.css']
})
export class CompletedFormsLibraryComponent implements OnInit {
  @ViewChild('modal') modal;
  tabTitle = 'Active';
  private dataTable: any;
  private tableWidget: any;
  Activestatus = true;
  Archivestatus = false;
  dataTableConfig;
  rowData;

  constructor(
    private el: ElementRef,
    private router: Router,
    private AppConfig: AppConfigService,
    private DMSAPirest: DMSAPIService
  ) {}

  ngOnInit() {
    this.loadDatatable('Active');
  }

  afterViewInit() {
    this.loadDatatable('Active');
  }
  tabSelectionChanged(tabTitle) {
    this.tabTitle = tabTitle;
    $(this.el.nativeElement.querySelector('table'))
      .DataTable()
      .destroy();
    // Get the selected tab
    if (tabTitle === 'Active') {
      this.loadDatatable('Active');
      this.Activestatus = true;
      this.Archivestatus = false;
    } else {
      this.loadDatatable('Archive');
      this.Activestatus = false;
      this.Archivestatus = true;
    }
  }

  private loadDatatable(tabTitle): void {
    let apiData;
    let recordsTotal;
    let recordsFiltered;
    let pageNumber;
    let actionName;
    let searchTerm = '';
    let pageSize;
    let param;
    const that = this;
     this.dataTableConfig = {
      processing: true,
      serverSide: true,
      paging: true,
      searching: { regex: true },
      lengthMenu: [[5, 10, 15, -1], [5, 10, 15, 'All']],
      ajax: function(data, callback, settings) {
        pageNumber = data.start / data.length + 1;
        actionName = tabTitle === 'Active' ? '0' : '1';
        searchTerm = data.search.value;
        pageSize = data.length;
        param = actionName + '/' + pageNumber + '/' + pageSize;
        if (searchTerm !== '') {
          param = param + '/' + searchTerm;
        }
        that.DMSAPirest.get(
          'FormsLibrary',
          'GetAssignedFormDetails',
          param
        ).subscribe(resp => {
          console.log(resp);
          apiData = resp.items;
          recordsTotal = resp.paging.totalItems;
          recordsFiltered = resp.paging.totalItems;
          callback({
            draw: data.draw,
            data: apiData,
            recordsTotal: recordsTotal,
            recordsFiltered: recordsFiltered
          });
        });
      },
      select: false,
      columns: [
        {
          title: 'Document Name',
          data: 'templateName',
          searchable: true
        },
        {
          title: 'Owner',
          data: 'ownerEmail',
          searchable: true,
          orderable: false
        },
        {
          title: 'Sent Date',
          data: 'sendDate',
          searchable: true,
          render: function(data, type, row, meta) {
            return (data ? moment(data).format('MM/DD/YYYY') : '');
          }
        },
        {
          title: 'Sender',
          data: 'senderName',
          orderable: false,
          searchable: true
        },
        {
          title: 'Receiver',
          data: 'reciverName',
          searchable: true
        },
        {
          title: 'Signed',
          data: 'signed',
          searchable: true,
          render: function(data, type, row, meta) {
            return (data === '1' ? 'Signed' : 'Not Signed');
          }
        },
        {
          title: 'Status',
          data: 'status',
          searchable: true,
          render: function(data, type, row, meta) {
            return 'Initial';
          }
        },
        {
          title: 'Action',
          data: 'actions',
          orderable: false,
          searchable: true,
          render: function(data, type, row, meta) {
            if (tabTitle === 'Active') {
              data =
                '<a id="download" title="Download" href="javascript:void(0);">' +
                '<i class="fa fa-arrow-down" aria-hidden="true"></i>' +
                '</a>' +
                ' | ' +
                '<a id="resend" title="Resend" href="javascript:void(0);">' +
                '<i class="fa fa-envelope" aria-hidden="true"></i>' +
                '</a>' +
                '|' +
                '<a id="archive" title="Archive" href="javascript:void(0);">' +
                '<i class="fa fa-archive" aria-hidden="true"></i>' +
                '</a>';
            } else {
              data =
                '<a id="delete" title="Delete" href="javascript:void(0);">' +
                '<i class="fa fa-trash" aria-hidden="true"></i>' +
                '</a>';
            }

            return data;
          }
        }
      ],
      // info: false,
      language: {
        infoFiltered: '',
        infoEmpty: '0 Results',
        sLengthMenu: 'Show _MENU_',
        sEmptyTable: 'No records found',
        info: '_TOTAL_ Results',
        paginate: {
          previous: '',
          next: ''
        },
        search: '<i class="fa fa-search"></i>',
        searchPlaceholder: 'Search',
        processing: 'Loading. Please wait...'
      },
      'fnDrawCallback': function() {
        if ( $('#data_table_paginate span a.paginate_button').length > 1 ) {
          $('#data_table_paginate')[0].style.display = 'block';
          $('.bottom .dataTables_paginate')[0].style.display = 'block';
        } else {
          $('#data_table_paginate')[0].style.display = 'none';
          $('.bottom .dataTables_paginate')[0].style.display = 'none';
        }
      },
      dom: '<"top"filp>rt<"bottom"ilp><"clear">'
    };

    this.dataTable = $(this.el.nativeElement.querySelector('table'));
    this.tableWidget = this.dataTable.DataTable(this.dataTableConfig);
    $('#data_table tbody').on('click', '#resend', function() {
      that.rowData = that.tableWidget.row($(this).parents('tr')).data();
      that.ResendForm(that.rowData.id);
    });
    $('#data_table tbody').on('click', '#download', function() {
      that.rowData = that.tableWidget.row($(this).parents('tr')).data();
      console.log('DownloadFile', that.rowData);
      that.DownloadFile(that.rowData.id, that.rowData.templateFileName);
    });
    $('#data_table tbody').on('click', '#delete', function() {
      that.rowData = that.tableWidget.row($(this).parents('tr')).data();
      console.log(that.rowData);
      console.log('delete', that.rowData.id);
      that.modal.showModal('delete');
    });

    $('#data_table tbody').on('click', '#archive', function() {
      that.rowData = that.tableWidget.row($(this).parents('tr')).data();
      // that.modal.showModal('archive');
      that.UpdateAsArchive(that.rowData.id);
    });

    $('#data_table_filter input').unbind();
    $('#data_table_filter input').bind('keyup', function(e) {
      if (e.keyCode === 13) {
        that.tableWidget.search($('#data_table_filter input').val()).draw();
      }
    });
  }

  DeleteDocument(id: number) {
    this.DMSAPirest.delete(
      'FormsLibrary',
      'DeleteDocumentCompleted',
      id
    ).subscribe(
      success => {
        if (success) {
          alert('document deleted');
          location.reload();
        }
      },
      error => {
        console.log(error.message);
      }
    );
  }

  UpdateAsArchive(id: number) {
    console.log(id);
    this.DMSAPirest.putData(
      'FormsLibrary',
      'ArchiveDocumentCompleted',
      id
    ).subscribe(
      success => {
        if (success) {
          console.log(this.modal);
          location.reload();
        }
      },
      error => {
        // console.log(error.message);
      }
    );
  }

  DownloadFile(id: number, templateFileName: string) {
    this.DMSAPirest.get('FileUpload', 'DownloadFileByTemplateID', id).subscribe(
      response => {
        if (response.statusCode === 400) {
          alert('file not found');
        } else if (response.statusCode === 200) {
          saveAs(
            this.AppConfig.getConfig().WebDowloadPath + templateFileName,
            templateFileName
          );
        }
      }
    );
  }

  ResendForm(id: number) {
    this.DMSAPirest.postData('FormsLibrary', 'ResendForm', id).subscribe(
      success => {
        if (success) {
          this.modal.showModal('resend');
          // alert('Email sent successfully.');
         // location.reload();
        }
      },
      error => {
        // console.log(error.message);
      }
    );
  }

  callApi($event) {
     if ($event === 'delete') {
      this.DeleteDocument(this.rowData.id);
    }
  }
}