import { Component, OnInit, ViewChild } from '@angular/core';
import { NgbModal, NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { NgxAnnotateTextComponent, Annotation } from 'ngx-annotate-text';
import { Subject } from 'rxjs';
import { ToastrService } from 'src/app/common-components/toastr/toastr.service';
import { CommonServiceLayerService, RequestPayLoadFormat } from 'src/app/services/common-service-layer.service';
import { SessionService } from 'src/app/services/session.service';
import jsonData from "../../../assets/jsons/text.json";

@Component({
  selector: 'app-landing',
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.scss']
})
export class LandingComponent implements OnInit {
  public fileTableReloadSubject: Subject<boolean> = new Subject<boolean>();
  public recordsTableReloadSubject: Subject<boolean> = new Subject<boolean>();

  @ViewChild('editPopup') editPopup;

  public tableSettings = { // table configs
    entity: '',
    tableActions: {
      show: true,
      actionButtons: [
        {
          class: 'action-info',
          icon: 'fa fa-eye',
          type: 'view',
          text: '',
          label: 'View',
          title: 'View',
          onlyText: false
        },
        {
          class: 'action-info text-center',
          icon: 'fa fa-trash',
          type: 'delete',
          label: 'Delete',
          onlyText: false,
          title: "Delete",
        }
      ]
    },
    columnSearch: {
      show: false,
      columnSearchToggle: false,
      searchExceptions: []
    },
    clickableColumns: {
      show: true,
      list: ['table_name'],
      class: 'clickable-element'
    },
    filters: {
      filterTable: false,
      showOnLoad: false,
      filterOptions: [],
      filterSelected: {
      }
    },
    addNew: false,
    addNewText: 'Import Data...',
    headerButtons: {
      show: false,
      buttons: [
        {
          text: '<i aria-hidden="true" class="fa fa-upload"></i> Bulk Upload',
          className: 'btn-new',
          key: '3',
          type: 'upload'
        }
      ]
    },
    emptyDataTemplate: {
      show: false,
      message: 'No Records available',
      filterBtn: {
        show: false,
        label: 'Filter data'
      }
    },
    stylings: {
      bodyHeight: 'calc(100vh - 360px)'
    },
    pageLength: 10,
    ordering: false
  };
  public tableData = {
    headerContent: [],
    bodyContent: [],
    records_filtered: 0,
    records_total: 0
  };
  public fileTableData = {
    tableActions: {
      actions: [
        {
          action: 'submit',
          label: 'Submit',
          type: 'submit',
          onlyIcon: false,
          class: 'action-info',
          icon: 'fa-paper-plane',
        },
      ],
      columnOptions: {
        dataset_name: {
          customColumnClass: 'medium-width',
        },
      },
      enableActions: true,
      itemsPerPage: {
        top: false,
      },
      columnSearch: {
        show: false,
        enable: false,
        searchExceptions: []
      },
      externalActions: [],
      columnSort: {
        enable: false,
        sortExceptions: [],
      },
      paginationOptions: {
        noOfItemsToDisplay: 10,
        displayOptions: [],
        show: false
      },
      showSerialNumber: false,
      stylings: {
        height: 'calc(100vh - 24rem)',
      },
      columnFilter: {
        show: false,
      },
    },
    tableData: {
      bodyContent: [],
      headerContent: [],
    },
    clickableColumns: {
      show: true,
      class: 'clickable-element',
      list: ['file_name'],
      iconList: ['file_name']
    },
  };
  public tableListData = {
    tableActions: {
      actions: [
        {
          action: 'view',
          label: 'View/ Edit',
          type: 'view',
          onlyIcon: true,
          class: 'action-info',
          icon: 'fa-eye',
        },
        {
          action: 'delete',
          label: 'Delete',
          type: 'delete',
          onlyIcon: true,
          class: 'action-info',
          icon: 'fa-trash',
        },
      ],
      columnOptions: {},
      enableActions: true,
      itemsPerPage: {
        top: false,
      },
      columnSearch: {
        show: false,
        enable: false,
        searchExceptions: []
      },
      externalActions: [],
      columnSort: {
        enable: false,
        sortExceptions: [],
      },
      paginationOptions: {
        noOfItemsToDisplay: 10,
        displayOptions: [],
        show: false
      },
      showSerialNumber: false,
      stylings: {
        height: 'calc(100vh - 24rem)',
      },
      columnFilter: {
        show: false,
      },
    },
    tableData: {
      bodyContent: [],
      headerContent: [],
    },
    clickableColumns: {
      show: true,
      class: 'clickable-element',
      list: ['table_name'],
      iconList: ['table_name']
    },
  };
  public showFileTable = true;
  public showRecordsTable = false;
  public selectedFileData;
  public selectedRecordData;
  public rowData;
  public saveTableFilterData;
  public modalOptions: NgbModalOptions = {
    size: 'xl',
    windowClass: 'standard-modal',
    backdrop: 'static',
    centered: true
  };
  public annotateData;
  constructor(
    private _toast: ToastrService,
    private http: CommonServiceLayerService,
    private modalService: NgbModal,
    private session: SessionService
  ) { }
  ngOnInit() {
    this.loadFileTableData({});
  }
  /**
   *  Get file grid data - landing view
   */
  loadFileTableData(data, hideLoader?) {
    try {
      const input = {
      };
      const request: RequestPayLoadFormat = {
        api: 'FILE_TABLE',
        // method: 'post',
        // type: 'API',
        method: 'get',
        type: 'JSON',
        loader: true,
        payLoad: data,
        hideErrorMessage: false
      };
      if (hideLoader) {
        request.loader = false;
      }
      this.http.API_REQUEST(request).subscribe((response) => {
        if (response.status === 'SUCCESS' && response.data) {
          this.fileTableData.tableData.headerContent = [];
          this.fileTableData.tableData.bodyContent = [];
          setTimeout(() => {
            this.fileTableData.tableData.headerContent = response.data.header_content || [];
            this.fileTableData.tableData.bodyContent = response.data.body_content || [];
          }, 100);
          // const tableData = {
          //   headerContent: response.data.header_content,
          //   bodyContent: response.data.body_content,
          //   records_filtered: 0,
          //   records_total: 0
          // }
          // this.tableData = tableData;
          // this.tableData.records_filtered = response.data.total_records;
          // this.tableData.records_total = response.data.total_records;
        } else {
          this._toast.toast('warning', 'Warning', response.message || 'Error while Loading data.', true);
        }
      });
    } catch (error) {
      console.error(error);
    }
  }

  /**
   * Method to handle file grid actions.
   */
  fileTableEmitter(event) {
    try {
      if (!event || !event.action || !event.action.type) { return; }
      this.selectedFileData = event.data;
      switch (event.action.type) {
        case 'fetchData':
          this.loadFileTableData({});
          break;
        case 'submit':
          if (event.data.status === 'Completed') {
            this._toast.toast('warning', '', 'The file has already been submitted.', true);
          } else {
            this.submitAllRecords();
          }
          break;
        case 'cellClick':
          if (event.data.status === 'Completed') {
            this._toast.toast('warning', '', 'The file has already been validated.', true);
          } else {
            this.loadRecordsTableData(event.data);
            this.showFileTable = false; this, this.showRecordsTable = true;
          }
          break;
      }
    } catch (error) {
      console.error(error);
    }
  }
  /**
   * Get Table-datatype grid data
   */
  loadRecordsTableData(data, hideLoader?) {
    try {
      const request: RequestPayLoadFormat = {
        api: 'REQUEST_TABLE',
        // method: 'post',
        // type: 'API',
        method: 'get',
        type: 'JSON',
        loader: true,
        payLoad: data,
        hideErrorMessage: false
      };
      if (hideLoader) {
        request.loader = false;
      }
      this.tableListData.tableData.headerContent = [];
      this.tableListData.tableData.bodyContent = [];
      this.http.API_REQUEST(request).subscribe((response) => {
        if (response.status === 'SUCCESS' && response.data) {
          // setTimeout(() => {
          //   this.tableListData.tableData.headerContent = response.data.header_content || [];
          //   this.tableListData.tableData.bodyContent = response.data.body_content || [];
          // }, 100);
          const tableData = {
            headerContent: response.data.header_content,
            bodyContent: response.data.body_content,
            records_filtered: 0,
            records_total: 0
          }
          this.tableData = tableData;
          this.tableData.records_filtered = response.data.total_records;
          this.tableData.records_total = response.data.total_records;
        } else {
          this._toast.toast('warning', 'Warning', response.message || 'Error while Loading data.', true);
        }
      });
    } catch (error) {
      console.error(error);
    }
  }
  /**
* @param val action performed on the table to add, edit, etc..
*/
  performAction(val) {
    try {
      if (!val || !val.action) { return; }
      val = JSON.parse(JSON.stringify(val));
      switch (val.action) {
        case 'fetchData':
          const postJson = this.selectedFileData;
          postJson['data_table_parameters'] = val.dataTableParameters;
          this.saveTableFilterData = postJson;
          this.loadRecordsTableData(this.saveTableFilterData);
          break;
        case 'cellEdit':
          this.selectedRecordData = val.data.row;
          this.getAnnotationsData(val.data.row);
          break;
        case 'view':
          this.selectedRecordData = val.data;
          this.getAnnotationsData(val.data);
          break;
        case 'delete':
          this.selectedRecordData = val.data;
          this.deleteRow(val.data);
          break;
        case 'addNew':
          break;
      }
    } catch (error) {
      console.log(error);
    }
  }
  /**
   * Method to handle Table grid actions.
   */
  recordsTableEmitter(event) {
    try {
      if (!event || !event.action || !event.action.type) { return; }
      this.selectedRecordData = event.data;
      switch (event.action.type) {
        case 'fetchData':
          this.loadRecordsTableData(this.selectedFileData);
          break;
        case 'cellClick':
          this.getAnnotationsData(event.data);
          break;
        case 'view':
          this.getAnnotationsData(event.data);
          break;
        case 'delete':
          this.deleteRow(event.data);
          break;
      }
    } catch (error) {
      console.error(error);
    }
  }
  /**
   * Method to delete file grid row.
   */
  deleteRow(data, hideLoader?) {
    try {
      let input = data;
      input['file_id'] = this.selectedFileData.file_id;
      input['file_name'] = this.selectedFileData.file_name;

      const request: RequestPayLoadFormat = {
        api: 'DELETE_ROW',
        // method: 'post',
        // type: 'API',
        method: 'get',
        type: 'JSON',
        loader: true,
        payLoad: input,
        hideErrorMessage: false
      };
      if (hideLoader) {
        request.loader = false;
      }
      this.http.API_REQUEST(request).subscribe((response) => {
        if (response.status === 'SUCCESS') {
          this._toast.toast('success', 'Success', response.message || 'Deleted Successfully', true);
          this.recordsTableReloadSubject.next(true);
        } else {
          this._toast.toast('warning', 'Warning', response.message || 'Error while Loading data.', true);
        }
      });
    } catch (error) {
      console.error(error);
    }
  }
  /**
   * Method to Get annotations, class details.
   */
  getAnnotationsData(data, hideLoader?) {
    try {
      let input = data;
      input['file_id'] = this.selectedFileData.file_id;
      input['file_name'] = this.selectedFileData.file_name;
      const request: RequestPayLoadFormat = {
        api: 'ANNOTATIONS_DATA',
        // method: 'post',
        // type: 'API',
        method: 'get',
        type: 'JSON',
        loader: true,
        payLoad: input,
        hideErrorMessage: false
      };
      if (hideLoader) {
        request.loader = false;
      }
      this.annotateData = [];
      this.http.API_REQUEST(request).subscribe((response) => {
        if (response.status === 'SUCCESS' && response.data) {
          this.annotateData = response.data;
          this.modalService.open(this.editPopup, this.modalOptions);
        } else {
          this._toast.toast('warning', 'Warning', response.message || 'Error while Loading data.', true);
        }
      });
    } catch (error) {
      console.error(error);
    }
  }
  /**
   * Method to Save annotations after editing.
   */
  saveAnnotations(e) {
    // console.log(JSON.stringify(e));
    let input = e;
    input['default_tag'] = this.selectedRecordData.data_type;
    input['table_name'] = this.selectedRecordData.table_name;
    input['data_type'] = this.selectedRecordData.data_type;
    input['file_id'] = this.selectedFileData.file_id;
    input['file_name'] = this.selectedFileData.file_name;
    try {
      const request: RequestPayLoadFormat = {
        api: 'SAVE_ANNOTATIONS',
        // method: 'post',
        // type: 'API',
        method: 'get',
        type: 'JSON',
        loader: true,
        payLoad: input,
        hideErrorMessage: false
      };
      this.http.API_REQUEST(request).subscribe((response) => {
        if (response.status === 'SUCCESS') {
          this._toast.toast('success', 'Success', response.message || 'Saved Successfully', true);
          this.recordsTableReloadSubject.next(true);
          this.closePopup();
        } else {
          this._toast.toast('warning', 'Warning', response.message || 'Error while Loading data.', true);
        }
      });
    } catch (error) {
      console.error(error);
    }
  }
  /**
   * Method to Submit all tables at table grid level and file grid level.
   */
  submitAllRecords() {
    try {
      const request: RequestPayLoadFormat = {
        api: 'SUBMIT_ALL_RECORDS',
        // method: 'post',
        // type: 'API',
        method: 'get',
        type: 'JSON',
        loader: true,
        payLoad: this.selectedFileData,
        hideErrorMessage: false
      };
      this.http.API_REQUEST(request).subscribe((response) => {
        if (response.status === 'SUCCESS' && response.data) {
          this._toast.toast('success', 'Success', response.message || 'Submitted Successfully', true);
          this.showFileTable = true; this, this.showRecordsTable = false;
          // this.fileTableReloadSubject.next(true);
          this.loadFileTableData({});
        } else {
          this._toast.toast('warning', 'Warning', response.message || 'Error while Loading data.', true);
        }
      });
    } catch (error) {
      console.error(error);
    }
  }

  closeTooltip() {
    setTimeout(() => {
      const tooltipClose = document.getElementsByClassName('tooltip');
      if (tooltipClose && tooltipClose.length > 0) {
        tooltipClose[0].remove();
      }
    });
  }
  closePopup() {
    try {
      this.modalService.dismissAll();
      this.closeTooltip();
    } catch (error) {
      console.log(error);
    }
  }
}
