
import { Component, OnInit, TemplateRef, ViewChild, ViewEncapsulation, } from '@angular/core';
import { ActivatedRoute, Router } from "@angular/router";

import { ToastrService } from 'ngx-toastr';
import { ExtensionField } from "src/app/models/fnd/ExtensionField";
import { ExtensionService } from 'src/app/services/fnd/extension.service';

//import { Teacher } from "src/app/pages/university/teacher/Teacher";
import { UserInfoService } from "src/app/services/user-info.service";
import { ApiRegisteryservice } from '../ApiRegistery.service';
import { FormBuilder, FormGroup } from '@angular/forms';

interface Rows {

  id: number;
  url: string;
  method: string;
  header_id: number;
}
@Component({
  selector: 'app-allapiregistery',
  templateUrl: './allapiregistery.component.html',
  styleUrls: ['./allapiregistery.component.scss']
})
export class AllapiregisteryComponent implements OnInit {
  @ViewChild("extById") extensionById: TemplateRef<any>;
  @ViewChild("showInGrid") txId: TemplateRef<any>;

  //@ViewChild("filter") filter: ElementRef;
  basic: boolean = false;
  // whoColumns: Teacher; // who columns data
  alldata: any;
  userrole;
  columns: any[];
  rows: Rows[];
  temp = [];
  rowSelected: any = {};
  modaldelete = false;
  modalEdit = false;
  modalAdd = false;
  public entryForm: FormGroup;
  loading = false;
  error;
  selected: any[] = [];
  filterData: string;
  isLoading: boolean = false;
  extensionField: ExtensionField[] = [];
  constructor(private router: Router,
    private route: ActivatedRoute,
    private toastr: ToastrService,
    private extensionService: ExtensionService,
    private apiregistery: ApiRegisteryservice,
    private userInfoService: UserInfoService,
    private _fb: FormBuilder,
  ) { }

  private account_id: any;
  // private formCode: any;
  formCode: string;
  getFormCode;
  public key: string = "formCode";
  public storage: Storage = sessionStorage;
  ngOnInit(): void {
    this.route.queryParams.subscribe(params => {
      this.getFormCode = params['formCode'];
      console.log("formCode ", this.getFormCode);
      this.storage.setItem("formCode", this.getFormCode); // Store the value in sessionStorage using the key
    });


    this.account_id = this.userInfoService.getUserId();
    this.formCode = this.storage.getItem(this.key);
    console.log("[ngOnInit] acc_id: " + this.account_id + " formCode: " + this.formCode);
    this.getData();
    // this.columns = [
    //   /* { prop: "id", name: "Actions", width: 65, cellTemplate: this.extensionById }, */
    //   { prop: "field_name", name: "Field Name", width: 120 },
    //   { prop: "mapping", name: "Mapping", width: 150 },
    //   { prop: "data_type", name: "Data Type", width: 190 },
    //   /* { prop: "id", name: "Show In Grid", width: 90, cellTemplate: this.txId } */
    // ];

    this.entryForm = this._fb.group({
      table_name: [null],
    });

    this.userrole = this.userInfoService.getRoles();

  }
  getData() {
    this.apiregistery.getAll().subscribe((data) => {
      this.alldata = data
      console.log(' get all ', this.alldata);
      if (this.alldata.length == 0) {
        this.error = "No data Available";
        console.log(this.error)
      }
    }, (error) => {
      console.log(error);
      if (error) {
        this.error = "Server Error";
      }
    })
  }

  alertType: string;
  alertMessage: string = "";
  alert = [
    { type: "success", message: "Build Successfully" },
    { type: "danger", message: "Some error Happens" },
  ];

  // buildExtension(id, accountID) {
  //   console.log("buildExtension() Account id = " + this.account_id + " Form Code = ",
  //     this.formCode);
  //   if (this.account_id === null && this.formCode === null) {
  //     this.alertType = this.alert[1].type;
  //     this.alertMessage = "form_code is null";
  //     return;
  //   }
  //   this.extensionService
  //     .buildExtension(id, accountID, this.formCode)
  //     .subscribe(
  //       (data) => {
  //         console.log("build successfully ", data);
  //         this.alert.forEach((e) => {
  //           if (e.type === "success") {
  //             this.alertType = e.type;
  //             this.alertMessage = e.message;
  //           } //data.type === true : e.message ? e.message

  //         });
  //         // go to parent entry form...
  //         //this.router.navigate(['../../'], { relativeTo: this.route.parent });

  //         if (data) {
  //           this.toastr.success("Build successfully");
  //         }


  //       },
  //       (err) => {

  //         if (err) {
  //           this.toastr.error("Build Not Successful");
  //         }
  //         console.log("build failed ", err);
  //         this.alertType = this.alert[1].type;
  //         this.alertMessage = this.alert[1].message;
  //       }
  //     );
  // }

  // isChecked(id: number) {
  //   return (
  //     this.extensionField.find(c => {
  //       if (c.id === id) return c.isActive;
  //     }) !== undefined
  //   );
  // }

  // chk(checked) {
  //   console.log(checked);
  //   return !checked;
  // }

  // extField: ExtensionField;
  // checked: boolean;
  // toggle(id: number) {
  //   console.log(id);
  //   this.extensionService.getById(id).subscribe(ext => {
  //     this.extField = ext;
  //     this.checked = ext.isActive;
  //     console.log('extField ', this.extField);
  //     console.log('checked ', this.checked);
  //   });
  //   console.log(this.extField.isActive);
  //   //this.extensionService.update(id,this.extField).subscribe();
  // }

  goToEdit(row) {
    this.rowSelected = row;

    this.modalEdit = true;
  }

  onUpdate(id) {
    this.modalEdit = false;
    //console.log("in update");
    console.log("id  " + id);
    console.log(this.rowSelected);
    //console.log("out update");
    this.apiregistery.update(id, this.rowSelected).subscribe(
      (data) => {
        console.log(data);
        if (data || data.status >= 200 && data.status <= 299) {
          this.toastr.success("Update Successfully");
        }
        setTimeout(() => {
          this.ngOnInit();
        }, 500);

      }, (error) => {
        console.log(error);
        if (error.status >= 200 && error.status <= 299) {
          // this.toastr.success("update Succesfully");
        }
        if (error.status >= 400 && error.status <= 499) {
          this.toastr.error("Not Updated");
        }
        if (error.status >= 500 && error.status <= 599) {
          this.toastr.error("Not Updated");
        }
      });
    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  }
  onCreate() {
    this.modalAdd = false;
    this.apiregistery.create(this.entryForm.value).subscribe(
      (data) => {
        console.log('after add ', data);
        if (data || data.status >= 200 && data.status <= 299) {
          this.toastr.success("Added Successfully");
        }
        setTimeout(() => {
          this.ngOnInit();
        }, 500);

      }, (error) => {
        console.log(error);
        if (error.status >= 200 && error.status <= 299) {
          // this.toastr.success("Added Succesfully");
        }
        if (error.status >= 400 && error.status <= 499) {
          this.toastr.error("Not Added");
        }
        if (error.status >= 500 && error.status <= 599) {
          this.toastr.error("Not Added");
        }
      });
    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  }
  goToAdd(row) {
    this.modalAdd = true;
    this.submitted = false;

  }
  submitted = false;
  onSubmit() {
    console.log(this.entryForm.value);
    this.submitted = true;
    if (this.entryForm.invalid) {
      return;
    } this.onCreate();

  }


  // goToAdd() {
  //   this.router.navigate(["../add"], { relativeTo: this.route });
  // }
  // goToEdit(id: number) {
  //   this.router.navigate(["../edit/" + id], { relativeTo: this.route });
  // }

  goToWhoColumns(id: number) {
    this.basic = !this.basic;
  }
  onDelete(row) {
    this.rowSelected = row;
    this.modaldelete = true;
  }
  delete(id) {
    this.modaldelete = false;
    console.log("in delete  " + id);
    this.extensionService.delete(id).subscribe((data) => {
      console.log(data);
      this.ngOnInit();
      if (data.body) {
        this.toastr.success('Deleted successfully');
      }
    }, (error) => {
      console.log('Error in adding data...', +error);
      if (error) {
        this.toastr.error('Not Deleted Data Getting Some Error');
      }
    });
  }


   gotoline(id: any) {
    this.router.navigate(["../line/" + id], { relativeTo: this.route })
  }
}
