import { Component, OnInit, TemplateRef } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog } from '@angular/material';
import { Router } from '@angular/router';
import { DialogService } from 'ng2-bootstrap-modal';
import { BsModalRef, BsModalService, ModalOptions } from 'ngx-bootstrap';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';
import { DashboardService } from 'src/app/dashboard/dashboard.service';
import { CommondialogComponent } from 'src/app/Shared/commondialog/commondialog.component';
import { StatecodeService } from '../statecode/statecode.service';
import { errormaster_model } from './errormaster_model';
import { ErrormasterService } from './errormaster.service';
import { environment } from 'src/environments/environment';
import signalR = require('@aspnet/signalr');
import toast from 'devextreme/ui/toast';

@Component({
  selector: 'app-errormaster',
  templateUrl: './errormaster.component.html',
  styleUrls: ['./errormaster.component.css']
})
export class ErrormasterComponent implements OnInit {

  p = 1; public searchText: string;
  operation:any;
  itemsPerPage = 10;
  errorModalRef: BsModalRef;
  errorForm: FormGroup;
  error_data: errormaster_model;
  config: ModalOptions = {
    backdrop: 'static',
    keyboard: false,
    animated: true,
    class: 'modal-dialog-centered',
    ignoreBackdropClick: true
  };
  userid: string = localStorage.getItem("userid");
  showall = true;
  showallstatus = false;
  actionRights: any; _menuId: any; readOnly: boolean; add: boolean =true; edit: boolean =true; delete: boolean; submitShow: boolean;
  useridnew: string = localStorage.getItem('userid');
  key = 'errortype';
  erroractive:errormaster_model[]=[];
  reverse = false;
  errorlst:errormaster_model[]=[];
  answerTable:any=[];
  baseUrl: string = environment.serviceUrl;

  stagelst:any=[];

  constructor(private error_service:ErrormasterService,
    private router: Router,
    private dialog: MatDialog,
    private formBuilder: FormBuilder,
    private modalService: BsModalService,
    private SpinnerService: NgxSpinnerService,
    private dashboardservice: DashboardService,
    private dialogService: DialogService,
    private toastr: ToastrService) {  
    // get rights for the logged in user for the particular component
      
      if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('Error_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('Error_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('Error_userRights');
    }
  }

  ngOnInit(): void {
    this.errorForm = this.formBuilder.group({
      errorid: [''],
      errortype: ['', [Validators.required]],
      errorcategory: [0, [Validators.required]],
      agentstage: [0, [Validators.required]],
      active: ['']
    });
    this.searchText = '';
    this.onload();

  }
  sort(key) {
    this.key = key;
    this.reverse = !this.reverse;
  }
  
  clearForm(){
    this.errorForm.controls['errorid'].setValue(0)
      this.errorForm.controls['errortype'].setValue('');
      this.errorForm.controls['errorcategory'].setValue('');
      this.errorForm.controls['agentstage'].setValue('');
      this.errorForm.controls['active'].setValue(0);
      this.errorModalRef.hide();
      this.add=false;
      this.edit=false;
  }

  onload(){
    this.error_service.Get_all().subscribe(res => {
      // debugger;
      if(res.body != null && res.body != undefined)
      {
        this.errorlst = JSON.parse(res.body.errorlst);
        this.stagelst = JSON.parse(res.body.stagelst);
      }
       this.SpinnerService.hide();
    }, error => {
      this.SpinnerService.hide();
      this.toastr.error('Error while getting Error list data');
    });
  }

  OpenConfirmTemplate(item: errormaster_model) {
    let confmsg;
// debugger;
    if (item.active === 0) {
      confmsg = 'activate';
      item.active=1;
    } else {
      confmsg = 'deactivate';
      item.active =0;
    }
    this.dialogService.addDialog(CommondialogComponent,
      {
        title: 'Please Confirm',
        message: 'Are you sure you want to ' + confmsg + ' this record ?',
        hclass: 'modelsuccess',
        oktext: 'Yes',
        canceltext: 'No',
        okshow: true,
        cancelshow: true
      }).subscribe((isConfirmed) => {
        if (isConfirmed) {
          this.Delete(item);
        }

      });
  }

  Delete(item:errormaster_model){
    // debugger;
    var inputData = [];
    inputData.push({
      updatedby: Number(localStorage.getItem('userid')),
      active:item.active,
      errorid:item.errorid
    })

    this.error_service.Active_Error(inputData[0]).subscribe(res => {
      // debugger;
      if(item.active == 0){
        this.toastr.success('Inactive the record successfully');
        
      }else{
        this.toastr.success('Active the record successfully');
      }
      this.onload();
  }, error => {
      this.toastr.error(error.error);
  });
  }

  getactiveinactive(showallp) {
    this.SpinnerService.show();
    this.erroractive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.errorlst.forEach(data => {
        if (data.active === 1) {
          this.erroractive.push(data);
        }
      });
      this.errorlst = [];
      this.errorlst = this.erroractive;
    } else {
      this.showall = true;
      this.errorlst = [];
      this.onload();
    }
    this.SpinnerService.hide();
  }

  Post(item:errormaster_model){
// debugger;
if(this.errorForm.valid){
  if(Number(item.errorcategory) == 0){
    this.toastr.error('Please select the error category')
    return;
  }

  if(item.agentstage == '' && item.agentstage.toString() == '0'){
    this.toastr.error('Please select the agent stage');
    return;
  }

  if(this.operation==='add'){
    var inputData = [];
    inputData.push({
      errortype: item.errortype,
      errorcategory: item.errorcategory,
      agentstage: item.agentstage,
      createdby: Number(localStorage.getItem('userid')),
      active:1
    });

    this.error_service.Add_Error(inputData[0]).subscribe(res => {
      // debugger;
      this.errorModalRef.hide();
      this.toastr.success('Successfully Added.');
      this.onload();
     //this.user_option=false;
    
  }, error => {
      this.toastr.error(error.error);
  });
  }else if(this.operation ==='update'){
    var inputData = [];
    inputData.push({
      errorid :item.errorid,
      errortype: item.errortype,
      errorcategory: item.errorcategory,
      agentstage: item.agentstage,
      updatedby: Number(localStorage.getItem('userid')),
      active:item.active,
    });

    this.error_service.Edit_Error(inputData[0]).subscribe(res => {
      // debugger;
      this.errorModalRef.hide();
      this.toastr.success('Successfully Updated.');
this.onload();
     //this.user_option=false;
    
  }, error => {
      this.toastr.error(error.error);
  });

  }

}else{
  this.toastr.error('Please fill the Required fields.');
}

  }

  

  ChangeActive(e) {
    if (e.currentTarget.checked) {
      this.errorForm.controls['active'].setValue(1);
    } else {
      this.errorForm.controls['active'].setValue(0);
    }
  }
  openCheckListModal(template: TemplateRef<any>, type, item?: errormaster_model) {
debugger;
    this.operation = type;

    if (type === 'update') {
      this.errorForm.controls['errorid'].setValue(item.errorid);
      this.errorForm.controls['errortype'].setValue(item.errortype);
      this.errorForm.controls['agentstage'].setValue(item.agentstage);
      this.errorForm.controls['errorcategory'].setValue(item.errorcategory);
      this.errorForm.controls['active'].setValue(item.active);
      this.add=false;
      this.edit=true;

    this.error_data = item;
    }
    if (type === 'add') {
      this.errorForm.controls['errortype'].setValue('');
      this.errorForm.controls['errorcategory'].setValue(0);
      this.errorForm.controls['agentstage'].setValue(0);
      this.errorForm.controls['active'].setValue(0);
      this.edit=false;
      this.add=true;
    }
    this.errorModalRef = this.modalService.show(template, this.config);

    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
  }

  callerrorremark(item){
    this.router.navigate(['/masters/errorremarks'], { queryParams: { errorid: item.errorid,errorcategory: item.errorcategory,errortype:item.errortype} });
  }

  AI_button(){
    
  this.answerTable =[
  {
     owner: [{
       Value: "Board of Supervisors of the County of Mariposa",
       IsCorrect: true
     }],
     project_name: [{
       Value: "West Whitlock, Jerseydale, and Wawona Storm Repair Project",
       IsCorrect: true
     }],
     state: [{
       Value: "California",
       IsCorrect: true
     }],
     city: [{
       Value: "Mariposa",
       IsCorrect: true
     }],
     construction_sites: [{
         Value: "W. Whitlock Road Headwall",
         IsCorrect: true
       },
       {
         Value: "Jerseydale Roadway Base Repairs",
         IsCorrect: true
       },
       {
         Value: "Jerseydale Road Embankment Repair",
         IsCorrect: true
       },
       {
         Value: "Jerseydale Double 48” RCP",
         IsCorrect: true
       },
       {
         Value: "Wawona Single 48” RCP",
         IsCorrect: true
       }
     ],
     scope: [{
       Value: "Repair of 5 locations affected by storms.",
       IsCorrect: true
     }],
     num_construction_projects: [{
       Value: 1,
       IsCorrect: true
     }],
     project_value: [{
       Value: "$900,000",
       IsCorrect: true
     }],
     bid_submission_datetime: [{
       Value: "2023-08-24T14:00:00",
       IsCorrect: true
     }],
     bid_submission_notes: [{
       Value: "Bids must be submitted on the form provided by the County to be considered.",
       IsCorrect: true
     }],
     pre_bid_datetime: [{
       Value: "2023-08-14T15:00:00",
       IsCorrect: true
     }],
     pre_bid_notes: [{
       Value: "Non-mandatory pre-bid meeting at the Public Works Dept Offices.",
       IsCorrect: true
     }],
     pre_bid_mandatory: [{
       Value: false,
       IsCorrect: true
     }],
     other_addresses_mentioned: [{
         Value: "4639 Ben Hur Rd. Mariposa, CA 95338",
         IsCorrect: true
       },
       {
         Value: "www.mariposacounty.org/Bids.aspx",
         IsCorrect: true
       }
     ],             
     labour_requirement: [{
       Value: "Contractor and subcontractors must pay workers at or above prevailing rates.",
       IsCorrect: true
     }],
     license_information: [{
       Value: "Bidders must be registered public works contractors with the Department of Industrial Relations and possess A-General Engineering license.",
       IsCorrect: true
     }]
   } ];
    const saveData = [];
    saveData.push({
      answerJson: JSON.stringify(this.answerTable),
      // answerJson: JSON.stringify(this.answerTable),
      buttonName: 'sam0',
      remark: 'sam1',
      status: 'sam2',
      projectId: 0,
    createdby:Number(this.useridnew)});
   /*this.saveData.answerJson = JSON.stringify(this.answerTable);
    this.saveData.buttonName = from;
    this.saveData.remarks = 'test';
    this.saveData.statu = 'test';
    this.saveData.projectId = 'proj';*/
    this.error_service.saveLobAnswer(saveData[0]).subscribe(res => {
    }, error => { this.toastr.error('Error while getting data'); });
  }


  singalr(){
    this.call_signal();
    const connection = new signalR.HubConnectionBuilder()
    .configureLogging(signalR.LogLevel.Information)
    .withUrl(this.baseUrl+'authhub')
    .build();

    connection.start().then(function(){
      console.log('Started SignalR and Connected');
      // this.toastr.success('connected');
    }).catch(function(err){
      // this.toastr.error(err.toString());
      return console.log(err.toString());
      
    });

    connection.on("BroadcastMessage",()=>{
      // this.toastr.warning('notified the API');
      this.print();

    })
  }

  print(){
    this.toastr.success('signalr message');
  }
  
  call_signal(){
    this.error_service.singal().subscribe(res=>{
      console.log('signalr demo',res);
    })
  }
}
