import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { CommonFunctionService } from 'src/app/core/common/common-function.service';
import { API } from 'src/app/core/services/api.service'
@Component({
  selector: 'app-activity-category-search',
  templateUrl: './activity-category-search.component.html',
})
export class ActivityCategorySearchComponent {

   Result;
   AllParentCategory;
  cols;
  categorySearchForm: FormGroup;

  constructor(
    public fb: FormBuilder,
    private apiserv: API,
    public commonMasterSer: CommonFunctionService,
    private router: Router
  ) {}

  ngOnInit(): void {
    this.cols = [
      { field: 'categoryName', header: 'Category Name' },
      { field: 'parentCategoryName', header: 'Parent Category' },
      { field: 'activityCategoryId', header: 'Category Id' },
      { field: 'status', header: 'Status' },
      { field: 'createdBy', header: 'Created By' },
      { field: 'Custom_created_on', header: 'Created On' },
      { field: 'updatedBy', header: 'Updated By' },
      { field: 'Custom_updated_on', header: 'Updated On' },
    ];

    this.initform();
    this.getParentCategory();
  }

  getParentCategory() {
    this.apiserv.Get(`/ActivityCategory/GetAllCategory`).subscribe(res => {
      if (res && res.status) {
        this.AllParentCategory = res.data;
      }
   });
  }

  initform() {
    this.categorySearchForm = this.fb.group({
      categoryName: '',
      parentCategoryId: ''
    });
  }

  Search() {
    let val = this.categorySearchForm.getRawValue();
    let ReqObj = {
      categoryName: val.categoryName ? val.categoryName : '',
      parentCategoryId: val.parentCategoryId ? val.parentCategoryId : ''
    };

    this.apiserv.Post('/ActivityCategory/GetAll', ReqObj).subscribe(res => {
      if (res) {
        this.Result = res.data ? res.data : [];
        if (res.data && res.status) {
          this.Result.forEach(e => {
            e['status'] = e.isActive ? 'Active' : 'Deactive';
            e['Custom_updated_on'] = this.commonMasterSer.convertDateWithTimeToShow(e.updatedOn);
            e['Custom_created_on'] = e['createdOn'] ? this.commonMasterSer.convertDateWithTimeToShow(e.createdOn) : e['createdOn'];
          });
        }
      }
    });
  }

  Reset() {
    this.categorySearchForm.reset();
  }

  Edit(id: string) {
    this.router.navigateByUrl(`ActivityConfiguration/ActivityCategory/Edit/${id}`);
  }

  ManageLang(id: string) {
    this.router.navigateByUrl(`ActivityConfiguration/ActivityCategory/Language/${id}`);
  }

  updateStatus(id: string, val: boolean) {
    let obj = {
      id: id,
      status: val ? false : true,
    };
    this.apiserv.Post('/ActivityCategory/UpdateStatus', obj).subscribe(res => {
      if (res) {
        this.commonMasterSer.showMessage(res['status'], res['message']);
        res['status'] ? this.Search() : '';
      }
    });
  }

}
