() => {
  // Arrange
  // @ts-ignore
  const fakeEmployeeRepository: EmployeeRepository = {
    // @ts-ignore
    findByNames: jest.fn(),
  };

  let employeeController;

  // @ts-ignore
  const fakeCommandDispatcher: SyncCommandDispatcher = {
    // @ts-ignore
    execute: jest.fn(),
  };

  employeeController = new EmployeeController(
    fakeCommandDispatcher,
    fakeEmployeeRepository,
  );

  describe('When an employee is posted to the controller', () => {
    it('Should dispatch create employee command', async () => {
      // Arrange
      const request: CreateEmployeeRequest = {
        accountNumber: 'test',
        address: 'San Pedro Sula, Calle 1, Casa 5',
        bankName: 'Promerica',
        birthdate: '1993-14-04',
        city: 'San Pedro Sula',
        country: 'Honduras',
        displayName: 'Jimmy',
        effectiveDate: '2018-22-10',
        companyEmail: 'jimmyramos@acklenavenue.com',
        firstName: 'Jimmy',
        gender: 'Male',
        lastName: 'Ramos',
        middleName: 'Josue',
        personalEmail: 'jimmybanegas93@gmail.com',
        phoneNumber: '50494621230',
        region: 'Cortes',
        salary: '10',
        salaryType: 'Montly',
        secondLastName: 'Banegas',
        startDate: '2019-22-02',
        tags: 'Developer',
      };

      // Act
      await employeeController.createEmployee(request);

      // Assert
      expect(fakeCommandDispatcher.execute).toBeCalledWith(request);
    });
  });

  describe('when an employee name UPDATE is sent to the controller', () => {
    it('should dispatch change employee name command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        firstName: 'Jimmy',
        lastName: 'Ramos',
        middleName: 'Josue',
        secondLastName: 'Banegas',
      };

      // Act
      await employeeController.changeNames(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  });
  describe('when an employee address UPDATE is sent to the controller', () => {
    it('should dispatch update employee address command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        address: 'San Pedro Sula, Calle 5, Casa 1',
        city: 'San Pedro Sula',
        country: 'Honduras',
        region: 'Cortes',
      };

      // Act
      await employeeController.changeAddress(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  });
  describe('when an employee display name UPDATE is sent to the controller', () => {
    it('should dispatch update employee display name command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        displayName: 'Jimmy',
      };

      // Act
      await employeeController.changeDisplayName(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  });
  describe('when an employee tags UPDATE is sent to the controller', () => {
    it('should dispatch update tags employee command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        tags: 'Developer',
      };

      // Act
      await employeeController.changeTags(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  });
  describe('when an employee phone number UPDATE is sent to the controller', () => {
    it('should dispatch update phone number employee command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        phoneNumber: '50494621230',
      };

      // Act
      await employeeController.changePhoneNumber(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  });
  describe('when an employee personal emaill UPDATE is sent to the controller', () => {
    it('should dispatch update personal email employee command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        personalEmail: 'jimmybanegas93@gmail.com',
      };

      // Act
      await employeeController.changePersonalEmail(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  });
  describe('when an employee company email UPDATE is sent to the controller', () => {
    it('should dispatch update employee company email command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        companyEmail: 'jimmyramos@acklenavenue.com',
      };

      // Act
      await employeeController.changeCompanyEmail(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  });
  describe('when an employee salary UPDATE is sent to the controller', () => {
    it('should dispatch update employee salary command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        salary: 10,
      };

      // Act
      await employeeController.changeSalary(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  });
  describe('when an employee salary type UPDATE is sent to the controller', () => {
    it('should dispatch update employee salary type command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        salaryType: 'Montly',
      };

      // Act
      await employeeController.changeSalaryType(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  });
  describe('when an employee effective date UPDATE is sent to the controller', () => {
    it('should dispatch update employee effective date command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        effectiveDate: '2018-22-10',
      };

      // Act
      await employeeController.changeEffectiveDate(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  });
  describe('when an employee UPDATE birthdate is sent to the controller', () => {
    it('should dispatch update employee birthdate command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        birthdate: '1993-14-04',
      };

      // Act
      await employeeController.changeBirthDate(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  });
  describe('when a UPDATE request is sent to the controller', () => {
    it('should disptach deactivateEmployee employee command', async () => {
      // Arrange
      const employee = { employeeId: 10, isActive: false };

      // Act
      await employeeController.deactivateEmployee(
        employee.employeeId,
        employee.isActive,
      );

      // Assert
      expect(fakeCommandDispatcher.execute).toBeCalledTimes(13);
    });
  });
  describe('when a UPDATE request is sent to the controller', () => {
    it('should disptach activateEmployee employee command', async () => {
      // Arrange
      const employee = { employeeId: 10, isActive: true };

      // Act
      await employeeController.activateEmployee(
        employee.employeeId,
        employee.isActive,
      );

      // Assert
      expect(fakeCommandDispatcher.execute).toBeCalledTimes(14);
    });
  });
}


() => {
    it('Should dispatch create employee command', async () => {
      // Arrange
      const request: CreateEmployeeRequest = {
        accountNumber: 'test',
        address: 'San Pedro Sula, Calle 1, Casa 5',
        bankName: 'Promerica',
        birthdate: '1993-14-04',
        city: 'San Pedro Sula',
        country: 'Honduras',
        displayName: 'Jimmy',
        effectiveDate: '2018-22-10',
        companyEmail: 'jimmyramos@acklenavenue.com',
        firstName: 'Jimmy',
        gender: 'Male',
        lastName: 'Ramos',
        middleName: 'Josue',
        personalEmail: 'jimmybanegas93@gmail.com',
        phoneNumber: '50494621230',
        region: 'Cortes',
        salary: '10',
        salaryType: 'Montly',
        secondLastName: 'Banegas',
        startDate: '2019-22-02',
        tags: 'Developer',
      };

      // Act
      await employeeController.createEmployee(request);

      // Assert
      expect(fakeCommandDispatcher.execute).toBeCalledWith(request);
    });
  }


async () => {
      // Arrange
      const request: CreateEmployeeRequest = {
        accountNumber: 'test',
        address: 'San Pedro Sula, Calle 1, Casa 5',
        bankName: 'Promerica',
        birthdate: '1993-14-04',
        city: 'San Pedro Sula',
        country: 'Honduras',
        displayName: 'Jimmy',
        effectiveDate: '2018-22-10',
        companyEmail: 'jimmyramos@acklenavenue.com',
        firstName: 'Jimmy',
        gender: 'Male',
        lastName: 'Ramos',
        middleName: 'Josue',
        personalEmail: 'jimmybanegas93@gmail.com',
        phoneNumber: '50494621230',
        region: 'Cortes',
        salary: '10',
        salaryType: 'Montly',
        secondLastName: 'Banegas',
        startDate: '2019-22-02',
        tags: 'Developer',
      };

      // Act
      await employeeController.createEmployee(request);

      // Assert
      expect(fakeCommandDispatcher.execute).toBeCalledWith(request);
    }


() => {
    it('should dispatch change employee name command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        firstName: 'Jimmy',
        lastName: 'Ramos',
        middleName: 'Josue',
        secondLastName: 'Banegas',
      };

      // Act
      await employeeController.changeNames(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  }


async () => {
      // Arrange
      const request = {
        employeeId: 100,
        firstName: 'Jimmy',
        lastName: 'Ramos',
        middleName: 'Josue',
        secondLastName: 'Banegas',
      };

      // Act
      await employeeController.changeNames(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    }


() => {
    it('should dispatch update employee address command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        address: 'San Pedro Sula, Calle 5, Casa 1',
        city: 'San Pedro Sula',
        country: 'Honduras',
        region: 'Cortes',
      };

      // Act
      await employeeController.changeAddress(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  }


async () => {
      // Arrange
      const request = {
        employeeId: 100,
        address: 'San Pedro Sula, Calle 5, Casa 1',
        city: 'San Pedro Sula',
        country: 'Honduras',
        region: 'Cortes',
      };

      // Act
      await employeeController.changeAddress(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    }


() => {
    it('should dispatch update employee display name command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        displayName: 'Jimmy',
      };

      // Act
      await employeeController.changeDisplayName(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  }


async () => {
      // Arrange
      const request = {
        employeeId: 100,
        displayName: 'Jimmy',
      };

      // Act
      await employeeController.changeDisplayName(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    }


() => {
    it('should dispatch update tags employee command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        tags: 'Developer',
      };

      // Act
      await employeeController.changeTags(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  }


async () => {
      // Arrange
      const request = {
        employeeId: 100,
        tags: 'Developer',
      };

      // Act
      await employeeController.changeTags(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    }


() => {
    it('should dispatch update phone number employee command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        phoneNumber: '50494621230',
      };

      // Act
      await employeeController.changePhoneNumber(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  }


async () => {
      // Arrange
      const request = {
        employeeId: 100,
        phoneNumber: '50494621230',
      };

      // Act
      await employeeController.changePhoneNumber(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    }


() => {
    it('should dispatch update personal email employee command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        personalEmail: 'jimmybanegas93@gmail.com',
      };

      // Act
      await employeeController.changePersonalEmail(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  }


async () => {
      // Arrange
      const request = {
        employeeId: 100,
        personalEmail: 'jimmybanegas93@gmail.com',
      };

      // Act
      await employeeController.changePersonalEmail(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    }


() => {
    it('should dispatch update employee company email command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        companyEmail: 'jimmyramos@acklenavenue.com',
      };

      // Act
      await employeeController.changeCompanyEmail(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  }


async () => {
      // Arrange
      const request = {
        employeeId: 100,
        companyEmail: 'jimmyramos@acklenavenue.com',
      };

      // Act
      await employeeController.changeCompanyEmail(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    }


() => {
    it('should dispatch update employee salary command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        salary: 10,
      };

      // Act
      await employeeController.changeSalary(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  }


async () => {
      // Arrange
      const request = {
        employeeId: 100,
        salary: 10,
      };

      // Act
      await employeeController.changeSalary(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    }


() => {
    it('should dispatch update employee salary type command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        salaryType: 'Montly',
      };

      // Act
      await employeeController.changeSalaryType(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  }


async () => {
      // Arrange
      const request = {
        employeeId: 100,
        salaryType: 'Montly',
      };

      // Act
      await employeeController.changeSalaryType(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    }


() => {
    it('should dispatch update employee effective date command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        effectiveDate: '2018-22-10',
      };

      // Act
      await employeeController.changeEffectiveDate(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  }


async () => {
      // Arrange
      const request = {
        employeeId: 100,
        effectiveDate: '2018-22-10',
      };

      // Act
      await employeeController.changeEffectiveDate(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    }


() => {
    it('should dispatch update employee birthdate command', async () => {
      // Arrange
      const request = {
        employeeId: 100,
        birthdate: '1993-14-04',
      };

      // Act
      await employeeController.changeBirthDate(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    });
  }


async () => {
      // Arrange
      const request = {
        employeeId: 100,
        birthdate: '1993-14-04',
      };

      // Act
      await employeeController.changeBirthDate(100, request);

      // Assert
      expect(fakeCommandDispatcher.execute).toHaveBeenCalledWith(request);
    }


() => {
    it('should disptach deactivateEmployee employee command', async () => {
      // Arrange
      const employee = { employeeId: 10, isActive: false };

      // Act
      await employeeController.deactivateEmployee(
        employee.employeeId,
        employee.isActive,
      );

      // Assert
      expect(fakeCommandDispatcher.execute).toBeCalledTimes(13);
    });
  }


async () => {
      // Arrange
      const employee = { employeeId: 10, isActive: false };

      // Act
      await employeeController.deactivateEmployee(
        employee.employeeId,
        employee.isActive,
      );

      // Assert
      expect(fakeCommandDispatcher.execute).toBeCalledTimes(13);
    }


() => {
    it('should disptach activateEmployee employee command', async () => {
      // Arrange
      const employee = { employeeId: 10, isActive: true };

      // Act
      await employeeController.activateEmployee(
        employee.employeeId,
        employee.isActive,
      );

      // Assert
      expect(fakeCommandDispatcher.execute).toBeCalledTimes(14);
    });
  }


async () => {
      // Arrange
      const employee = { employeeId: 10, isActive: true };

      // Act
      await employeeController.activateEmployee(
        employee.employeeId,
        employee.isActive,
      );

      // Assert
      expect(fakeCommandDispatcher.execute).toBeCalledTimes(14);
    }


@Injectable({
  providedIn: 'root'
})
export class ErrorHandlerService {

  constructor() { }
}


(mappingsQuery: UseQueryResult<IKubeList<Mapping>>) => {
  const isSaveNewMapping = useFormField(false, yup.boolean().required());
  const newMappingNameSchema = getMappingNameSchema(mappingsQuery, null).label('Name');
  return useFormState({
    isCreateMappingSelected: useFormField(false, yup.boolean().required()),
    selectedExistingMapping: useFormField<Mapping | null>(null, yup.mixed<Mapping | null>()),
    builderItems: useFormField<IMappingBuilderItem[]>([], mappingBuilderItemsSchema),
    isSaveNewMapping,
    newMappingName: useFormField(
      '',
      isSaveNewMapping.value ? newMappingNameSchema.required() : yup.string()
    ),
    isPrefilled: useFormField(false, yup.boolean()),
  });
}


(
  plansQuery: UseQueryResult<IKubeList<IPlan>>,
  networkMappingsQuery: UseQueryResult<IKubeList<Mapping>>,
  storageMappingsQuery: UseQueryResult<IKubeList<Mapping>>,
  planBeingPrefilled: IPlan | null,
  wizardMode: PlanWizardMode
) => {
  const forms = {
    general: useFormState({
      planName: useFormField(
        '',
        getPlanNameSchema(plansQuery, planBeingPrefilled, wizardMode).label('Plan name').required()
      ),
      planDescription: useFormField('', yup.string().label('Plan description').defined()),
      sourceProvider: useFormField<SourceInventoryProvider | null>(
        null,
        yup.mixed<SourceInventoryProvider>().label('Source provider').required()
      ),
      targetProvider: useFormField<IOpenShiftProvider | null>(
        null,
        yup.mixed<IOpenShiftProvider>().label('Target provider').required()
      ),
      targetNamespace: useFormField('', dnsLabelNameSchema.label('Target namespace').required()),
      migrationNetwork: useFormField<string | null>(
        null,
        yup.mixed<string>().label('Migration network')
      ),
    }),
    filterVMs: useFormState({
      treeType: useFormField<InventoryTreeType>(
        InventoryTreeType.Cluster,
        yup.mixed<InventoryTreeType>()
      ),
      selectedTreeNodes: useFormField<InventoryTree[]>(
        [],
        yup.array<InventoryTree>().required().min(1)
      ),
      isPrefilled: useFormField(false, yup.boolean()),
    }),
    selectVMs: useFormState({
      selectedVMIds: useFormField<string[]>(
        [],
        yup.array(yup.string().default('')).required().min(1)
      ),
    }),
    networkMapping: useMappingFormState(networkMappingsQuery),
    storageMapping: useMappingFormState(storageMappingsQuery),
    type: useFormState({
      type: useFormField<PlanType>('Cold', yup.mixed().oneOf(['Cold', 'Warm']).required()),
    }),
    hooks: useFormState({
      instances: useFormField<PlanHookInstance[]>([], yup.array<PlanHookInstance>()),
    }),
  };

  return {
    ...forms,
    isSomeFormDirty: (Object.keys(forms) as (keyof typeof forms)[]).some(
      (key) => forms[key].isDirty
    ),
  };
}


(key) => forms[key].isDirty


() => {
  const history = useHistory();
  const plansQuery = usePlansQuery();
  const networkMappingsQuery = useMappingsQuery(MappingType.Network);
  const storageMappingsQuery = useMappingsQuery(MappingType.Storage);

  const editRouteMatch = useRouteMatch<{ planName: string }>({
    path: '/plans/:planName/edit',
    strict: true,
    sensitive: true,
  });
  const duplicateRouteMatch = useRouteMatch<{ planName: string }>({
    path: '/plans/:planName/duplicate',
    strict: true,
    sensitive: true,
  });
  const wizardMode = editRouteMatch ? 'edit' : duplicateRouteMatch ? 'duplicate' : 'create';

  const prefillPlanName = editRouteMatch?.params.planName || duplicateRouteMatch?.params.planName;
  const planBeingPrefilled =
    plansQuery.data?.items.find((plan) => plan.metadata.name === prefillPlanName) || null;

  const forms = usePlanWizardFormState(
    plansQuery,
    networkMappingsQuery,
    storageMappingsQuery,
    planBeingPrefilled,
    wizardMode
  );

  const vmsQuery = useSourceVMsQuery(forms.general.values.sourceProvider);

  const { isDonePrefilling, prefillQueries, prefillErrorTitles } = usePlanWizardPrefillEffect(
    forms,
    planBeingPrefilled,
    wizardMode
  );

  enum StepId {
    General = 0,
    FilterVMs,
    SelectVMs,
    NetworkMapping,
    StorageMapping,
    Type,
    Hooks,
    Review,
  }

  const stepForms = [
    forms.general,
    forms.filterVMs,
    forms.selectVMs,
    forms.networkMapping,
    forms.storageMapping,
    forms.type,
    forms.hooks,
  ];
  const firstInvalidFormIndex = stepForms.findIndex((form) => !form.isValid);
  const stepIdReached: StepId =
    firstInvalidFormIndex === -1 ? StepId.Review : firstInvalidFormIndex;

  const onClose = () => history.push('/plans');

  const createPlanMutation = useCreatePlanMutation();
  const patchPlanMutation = usePatchPlanMutation();

  const { network: createSharedNetworkMapMutation, storage: createSharedStorageMapMutation } =
    useCreateMappingMutations();

  const createSharedMappings = async () => {
    const { networkMapping, storageMapping } = generateMappings({ forms });
    if (networkMapping && forms.networkMapping.values.isSaveNewMapping) {
      createSharedNetworkMapMutation.mutate(networkMapping);
    }
    if (storageMapping && forms.storageMapping.values.isSaveNewMapping) {
      createSharedStorageMapMutation.mutate(storageMapping);
    }
  };

  const onSave = () => {
    if (wizardMode === 'create' || wizardMode === 'duplicate') {
      createPlanMutation.mutate(forms);
    } else if (wizardMode === 'edit' && planBeingPrefilled) {
      patchPlanMutation.mutate({ planBeingEdited: planBeingPrefilled, forms });
    }
    createSharedMappings();
  };

  const allMutationResults = [
    !editRouteMatch ? createPlanMutation : patchPlanMutation,
    ...(forms.networkMapping.values.isSaveNewMapping ? [createSharedNetworkMapMutation] : []),
    ...(forms.storageMapping.values.isSaveNewMapping ? [createSharedStorageMapMutation] : []),
  ];
  const allMutationErrorTitles = [
    !editRouteMatch ? 'Cannot create migration plan' : 'Cannot save migration plan',
    ...(forms.networkMapping.values.isSaveNewMapping ? ['Cannot create network mapping'] : []),
    ...(forms.storageMapping.values.isSaveNewMapping ? ['Cannot create storage mapping'] : []),
  ];
  const mutationStatus = getAggregateQueryStatus(allMutationResults);

  React.useEffect(() => {
    if (mutationStatus === 'success') onClose();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [mutationStatus]);

  const selectedVMs = vmsQuery.data?.findVMsByIds(forms.selectVMs.values.selectedVMIds) || [];

  const clusterTreeQuery = useInventoryTreeQuery(
    forms.general.values.sourceProvider,
    InventoryTreeType.Cluster
  );
  const vmTreeQuery = useInventoryTreeQuery(
    forms.general.values.sourceProvider,
    InventoryTreeType.VM
  );

  const steps: WizardStep[] = [
    {
      id: StepId.General,
      name: 'General',
      component: (
        <WizardStepContainer title="General settings">
          <GeneralForm
            form={forms.general}
            wizardMode={wizardMode}
            afterProviderChange={()


(plan) => plan.metadata.name === prefillPlanName


(form) => !form.isValid


() => history.push('/plans')


async () => {
    const { networkMapping, storageMapping } = generateMappings({ forms });
    if (networkMapping && forms.networkMapping.values.isSaveNewMapping) {
      createSharedNetworkMapMutation.mutate(networkMapping);
    }
    if (storageMapping && forms.storageMapping.values.isSaveNewMapping) {
      createSharedStorageMapMutation.mutate(storageMapping);
    }
  }


() => {
    if (wizardMode === 'create' || wizardMode === 'duplicate') {
      createPlanMutation.mutate(forms);
    } else if (wizardMode === 'edit' && planBeingPrefilled) {
      patchPlanMutation.mutate({ planBeingEdited: planBeingPrefilled, forms });
    }
    createSharedMappings();
  }


() => {
    if (mutationStatus === 'success') onClose();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }


(_newStep, prevStep) => {
    if (prevStep.prevId === StepId.Review) {
      allMutationResults.forEach((result) => result.reset());
    }
  }


(result) => result.reset()


(c) => c.toUpperCase()


enum StepId {
    General = 0,
    FilterVMs,
    SelectVMs,
    NetworkMapping,
    StorageMapping,
    Type,
    Hooks,
    Review,
  }


export type PlanWizardMode = 'create' | 'edit' | 'duplicate';


export type PlanWizardFormState = ReturnType<typeof usePlanWizardFormState>;


UseQueryResult<IndexedTree


([, v]) => v === value


(bp1, bp2) => {
           if (checkDistinct) {
             return JSON.stringify(bp1.breakpoints) === JSON.stringify(bp2.breakpoints);
           } else {
             return false;
           }
         }


(result: BreakpointState) => {
         // console.log("  --> AppLayoutService|result: ", result);
         this._activatedBreakpoints.length = 0;
         Object.keys(result.breakpoints).map((keyAsValue) => {

           if (result.breakpoints[keyAsValue]) {
             // console.log("  --> AppLayoutService|keyAsValue: ", keyAsValue);
             const matchKV = this.findBPKeys(this._customBreakpoints, keyAsValue);
             // console.log("  ==> matchKV: ", matchKV);
             this._activatedBreakpoints.push(matchKV);
           }
         });
         // console.log(" --> AppLayoutService:_activatedBreakpoints: ", this._activatedBreakpoints);
         return this._activatedBreakpoints;
       }


(keyAsValue) => {

           if (result.breakpoints[keyAsValue]) {
             // console.log("  --> AppLayoutService|keyAsValue: ", keyAsValue);
             const matchKV = this.findBPKeys(this._customBreakpoints, keyAsValue);
             // console.log("  ==> matchKV: ", matchKV);
             this._activatedBreakpoints.push(matchKV);
           }
         }


bp => bp === bpTarget


@Injectable({
   providedIn: 'root'
 })
 export class ResponsiveLayoutService implements OnDestroy {

   private _activatedBreakpoints: string[] = [];
   public _customBreakpoints: { [key: string]: string; };

   public _preserveBP$: BehaviorSubject<any> = new BehaviorSubject<any>('');
   public preserveBP$ = this._preserveBP$.asObservable();

   constructor(
     private bpObserver: BreakpointObserver
   ) {
     // console.log("AppLayoutService contructor!");
   }

   ngOnDestroy(): void {
     // console.log("AppLayoutService|ngOnDestroy!")
   }

   _configureCustomBreakPoints(
     paramsArg?: BPConfigParams<BPMetric>
   ) {

     let params: Partial<BPConfigParams<BPMetric>> = {};
     params.xxs = { maxWidth: 299.99 }; //Watch, Tiny IoT devices...
     params.xs = { minWidth: 300, maxWidth: 898.99 };
     params.s = { minWidth: 899, maxWidth: 1387.99 };
     params.m = { minWidth: 1388, maxWidth: 1749.99 };
     params.l = { minWidth: 1750, maxWidth: 2149.99 };
     params.xl = { minWidth: 2150, maxWidth: 2399.99 };
     params.xxl = { minWidth: 2400 }; //Super Big Screen with High resolutions
     params.offset1 = 240; //major offset
     params.offset2 = 0; //minor offset
     params.handset = {
       maxWidthPortrait: params.xs.maxWidth, maxWidthLandscape: params.s.maxWidth
     };
     params.tablet = {
       minWidthPortrait: params.s.minWidth, maxWidthPortrait: params.s.minWidth + params.offset1 - 0.1, minWidthLandscape: params.m.minWidth, maxWidthLandscape: params.m.maxWidth
     };
     params.web = {
       minWidthPortrait: params.s.minWidth + params.offset1, minWidthLandscape: params.l.minWidth
     };

     if (paramsArg) {
       params = { ...params, ...paramsArg };
     }

     this._customBreakpoints = {
       XXSmall: `(max-width: ${params.xxs.maxWidth}px)`,
       XSmall: `(max-width: ${params.xs.maxWidth}px)and (max-width: ${params.xs.maxWidth}px)`,
       Small: `(min-width: ${params.s.minWidth}px) and (max-width: ${params.s.maxWidth}px)`,
       Medium: `(min-width: ${params.m.minWidth}px) and (max-width: ${params.m.maxWidth}px)`,
       Large: `(min-width: ${params.l.minWidth}px) and (max-width: ${params.l.maxWidth}px)`,
       XLarge: `(min-width: ${params.xl.minWidth}px) and (max-width: ${params.xl.maxWidth}px)`,
       XXLarge: `(min-width: ${params.xxl.minWidth}px)`,

       Handset: `(max-width: ${params.handset.maxWidthPortrait}px) and (orientation: portrait), ` +
         `(max-width: ${params.handset.maxWidthLandscape}px) and (orientation: landscape)`,
       Tablet: `(min-width: ${params.tablet.minWidthPortrait}px) and (max-width: ${params.tablet.maxWidthPortrait}px) and (orientation: portrait), ` +
         `(min-width: ${params.tablet.minWidthLandscape}px) and (max-width: ${params.tablet.maxWidthLandscape}px) and (orientation: landscape)`,
       Web: `(min-width: ${params.web.minWidthPortrait}px) and (orientation: portrait), ` +
         `(min-width: ${params.web.minWidthLandscape}px) and (orientation: landscape)`,

       HandsetPortrait: `(max-width: ${params.handset.maxWidthPortrait}px) and (orientation: portrait)`,
       TabletPortrait: `(min-width: ${params.tablet.minWidthPortrait}px) and (max-width: ${params.tablet.maxWidthPortrait}px) and (orientation: portrait)`,
       WebPortrait: `(min-width: ${params.web.minWidthPortrait}px) and (orientation: portrait)`,

       HandsetLandscape: `(max-width: ${params.handset.maxWidthLandscape}px) and (orientation: landscape)`,
       TabletLandscape: `(min-width: ${params.tablet.minWidthLandscape}px) and (max-width: ${params.tablet.maxWidthLandscape}px) and (orientation: landscape)`,
       WebLandscape: `(min-width: ${params.web.minWidthLandscape}px) and (orientation: landscape)`
     };

     // console.log("  --> _customBreakpoints: ", this._customBreakpoints);

   };

   getCustomBPValues() {
     return Object.values(this._customBreakpoints);
   }

   findBPKeys(target: Object, value: string) {
     return Object.entries(target).find(([, v]) => v === value)[0];
   }

   observeBreakpoints(checkDistinct: boolean = false, params?: BPConfigParams<BPMetric>): Observable<string[]> {

     if (!this._customBreakpoints) {
       this._configureCustomBreakPoints(params);
     }

     return this.bpObserver.observe(this.getCustomBPValues()).pipe(

       distinctUntilChanged(

         (bp1, bp2) => {
           if (checkDistinct) {
             return JSON.stringify(bp1.breakpoints) === JSON.stringify(bp2.breakpoints);
           } else {
             return false;
           }
         }
       ),

       map((result: BreakpointState) => {
         // console.log("  --> AppLayoutService|result: ", result);
         this._activatedBreakpoints.length = 0;
         Object.keys(result.breakpoints).map((keyAsValue) => {

           if (result.breakpoints[keyAsValue]) {
             // console.log("  --> AppLayoutService|keyAsValue: ", keyAsValue);
             const matchKV = this.findBPKeys(this._customBreakpoints, keyAsValue);
             // console.log("  ==> matchKV: ", matchKV);
             this._activatedBreakpoints.push(matchKV);
           }
         });
         // console.log(" --> AppLayoutService:_activatedBreakpoints: ", this._activatedBreakpoints);
         return this._activatedBreakpoints;
       })
     );
   }

   isActivated(bpTarget: string) {
     return this._activatedBreakpoints.find(bp => bp === bpTarget);
   }

 }


export interface BPMetric {
   minWidth?: number,
   maxWidth?: number;
   minWidthPortrait?: number;
   maxWidthPortrait?: number;
   minWidthLandscape?: number;
   maxWidthLandscape?: number;
 }


export interface BPConfigParams<T extends BPMetric> {
   xxs: T;
   xs: T;
   s: T;
   m: T;
   l: T;
   xl: T;
   xxl: T;
   offset1: number;
   offset2: number;
   watch?: T;
   handset?: T;
   tablet?: T;
   web?: T;
   smartTV?: T;
 }


ngOnDestroy(): void {
     // console.log("AppLayoutService|ngOnDestroy!")
   }


_configureCustomBreakPoints(
     paramsArg?: BPConfigParams<BPMetric>
   ) {

     let params: Partial<BPConfigParams<BPMetric>> = {};
     params.xxs = { maxWidth: 299.99 }; //Watch, Tiny IoT devices...
     params.xs = { minWidth: 300, maxWidth: 898.99 };
     params.s = { minWidth: 899, maxWidth: 1387.99 };
     params.m = { minWidth: 1388, maxWidth: 1749.99 };
     params.l = { minWidth: 1750, maxWidth: 2149.99 };
     params.xl = { minWidth: 2150, maxWidth: 2399.99 };
     params.xxl = { minWidth: 2400 }; //Super Big Screen with High resolutions
     params.offset1 = 240; //major offset
     params.offset2 = 0; //minor offset
     params.handset = {
       maxWidthPortrait: params.xs.maxWidth, maxWidthLandscape: params.s.maxWidth
     };
     params.tablet = {
       minWidthPortrait: params.s.minWidth, maxWidthPortrait: params.s.minWidth + params.offset1 - 0.1, minWidthLandscape: params.m.minWidth, maxWidthLandscape: params.m.maxWidth
     };
     params.web = {
       minWidthPortrait: params.s.minWidth + params.offset1, minWidthLandscape: params.l.minWidth
     };

     if (paramsArg) {
       params = { ...params, ...paramsArg };
     }

     this._customBreakpoints = {
       XXSmall: `(max-width: ${params.xxs.maxWidth}px)`,
       XSmall: `(max-width: ${params.xs.maxWidth}px)and (max-width: ${params.xs.maxWidth}px)`,
       Small: `(min-width: ${params.s.minWidth}px) and (max-width: ${params.s.maxWidth}px)`,
       Medium: `(min-width: ${params.m.minWidth}px) and (max-width: ${params.m.maxWidth}px)`,
       Large: `(min-width: ${params.l.minWidth}px) and (max-width: ${params.l.maxWidth}px)`,
       XLarge: `(min-width: ${params.xl.minWidth}px) and (max-width: ${params.xl.maxWidth}px)`,
       XXLarge: `(min-width: ${params.xxl.minWidth}px)`,

       Handset: `(max-width: ${params.handset.maxWidthPortrait}px) and (orientation: portrait), ` +
         `(max-width: ${params.handset.maxWidthLandscape}px) and (orientation: landscape)`,
       Tablet: `(min-width: ${params.tablet.minWidthPortrait}px) and (max-width: ${params.tablet.maxWidthPortrait}px) and (orientation: portrait), ` +
         `(min-width: ${params.tablet.minWidthLandscape}px) and (max-width: ${params.tablet.maxWidthLandscape}px) and (orientation: landscape)`,
       Web: `(min-width: ${params.web.minWidthPortrait}px) and (orientation: portrait), ` +
         `(min-width: ${params.web.minWidthLandscape}px) and (orientation: landscape)`,

       HandsetPortrait: `(max-width: ${params.handset.maxWidthPortrait}px) and (orientation: portrait)`,
       TabletPortrait: `(min-width: ${params.tablet.minWidthPortrait}px) and (max-width: ${params.tablet.maxWidthPortrait}px) and (orientation: portrait)`,
       WebPortrait: `(min-width: ${params.web.minWidthPortrait}px) and (orientation: portrait)`,

       HandsetLandscape: `(max-width: ${params.handset.maxWidthLandscape}px) and (orientation: landscape)`,
       TabletLandscape: `(min-width: ${params.tablet.minWidthLandscape}px) and (max-width: ${params.tablet.maxWidthLandscape}px) and (orientation: landscape)`,
       WebLandscape: `(min-width: ${params.web.minWidthLandscape}px) and (orientation: landscape)`
     };

     // console.log("  --> _customBreakpoints: ", this._customBreakpoints);

   }


getCustomBPValues() {
     return Object.values(this._customBreakpoints);
   }


findBPKeys(target: Object, value: string) {
     return Object.entries(target).find(([, v]) => v === value)[0];
   }


observeBreakpoints(checkDistinct: boolean = false, params?: BPConfigParams<BPMetric>): Observable<string[]> {

     if (!this._customBreakpoints) {
       this._configureCustomBreakPoints(params);
     }

     return this.bpObserver.observe(this.getCustomBPValues()).pipe(

       distinctUntilChanged(

         (bp1, bp2) => {
           if (checkDistinct) {
             return JSON.stringify(bp1.breakpoints) === JSON.stringify(bp2.breakpoints);
           } else {
             return false;
           }
         }
       ),

       map((result: BreakpointState) => {
         // console.log("  --> AppLayoutService|result: ", result);
         this._activatedBreakpoints.length = 0;
         Object.keys(result.breakpoints).map((keyAsValue) => {

           if (result.breakpoints[keyAsValue]) {
             // console.log("  --> AppLayoutService|keyAsValue: ", keyAsValue);
             const matchKV = this.findBPKeys(this._customBreakpoints, keyAsValue);
             // console.log("  ==> matchKV: ", matchKV);
             this._activatedBreakpoints.push(matchKV);
           }
         });
         // console.log(" --> AppLayoutService:_activatedBreakpoints: ", this._activatedBreakpoints);
         return this._activatedBreakpoints;
       })
     );
   }


isActivated(bpTarget: string) {
     return this._activatedBreakpoints.find(bp => bp === bpTarget);
   }


(err) => err.message


export type RebalanceProfile = Static<typeof RebalanceProfileSchema>;


export type AllowedSwap = Static<typeof AllowedSwapSchema>;


type VectorRouterConfig = Static<typeof VectorRouterConfigSchema>;


(tokens: Array<Token>): Node => {
  must(tokens.pop(), TokenType.if)
  const condition = expression(tokens)
  const inNode = (() => {
    if (nextIs(tokens, TokenType.in)) {
      tokens.pop()
      return expression(tokens)
    } else return undefined
  })()
  if (nextIsJoin(tokens)) return new IfNode(join(tokens), condition, inNode)
  else return new IfNode(new TitanNode(), condition, inNode)
}


() => {
    if (nextIs(tokens, TokenType.in)) {
      tokens.pop()
      return expression(tokens)
    } else return undefined
  }


blue_applications => {

            this.varModel.PHYSICAL_MEMORY_UTIL_AVG = blue_applications['value'].map(blue_applications => blue_applications.PHYSICAL_MEMORY_UTIL_AVG);
            this.varModel.SERVING_DEVICE_NAME = blue_applications['value'].map(blue_applications => blue_applications.SERVING_DEVICE_NAME);
            this.varModel.CPU_UTILIZATION_AVG = blue_applications['value'].map(blue_applications => blue_applications.CPU_UTILIZATION_AVG);
            this.varModel.DISK_QUEUE_LENGTH_MAX = blue_applications['value'].map(blue_applications => blue_applications.DISK_QUEUE_LENGTH_MAX);

            this.varModel.USERNAME = blue_applications['value'].map(blue_applications => blue_applications.USERNAME);
            this.varModel.VIRTUAL_MEMORY_UTIL_AVG = blue_applications['value'].map(blue_applications => blue_applications.VIRTUAL_MEMORY_UTIL_AVG);
            this.varModel.NETWORK_READ_AVG = blue_applications['value'].map(blue_applications => blue_applications.NETWORK_READ_AVG);
            this.varModel.NETWORK_WRITE_AVG = blue_applications['value'].map(blue_applications => blue_applications.NETWORK_WRITE_AVG);
            this.varModel.HOUR_RUNNING_TOTAL = blue_applications['value'].map(blue_applications => blue_applications.HOUR_RUNNING_TOTAL);
            this.varModel.DISK_IO_READ_AVG = blue_applications['value'].map(blue_applications => blue_applications.DISK_IO_READ_AVG);
            this.varModel.DISK_IO_WRITE_AVG = blue_applications['value'].map(blue_applications => blue_applications.DISK_IO_WRITE_AVG);

            this.device_name = new Set(this.varModel.SERVING_DEVICE_NAME);
            console.log(this.device_name);
           /* console.log(cpu_util_avg);
            console.log(disk_queue_length);
            console.log(virtual_memory);
            console.log(network_write_avg);
            console.log(DISK_IO_READ_AVG); **/

            this.barChartData = [

                { data: this.varModel.CPU_UTILIZATION_AVG, label: 'Cpu Avg' },
                { data: this.varModel.PHYSICAL_MEMORY_UTIL_AVG, label: 'Memory%' },
                { data: this.varModel.DISK_QUEUE_LENGTH_MAX, label: 'DQL' },
                { data: this.varModel.VIRTUAL_MEMORY_UTIL_AVG, label: 'Virtual Memory' }
            ];

           /* this.doughnutChartData = [network_read_avg, network_write_avg, DISK_IO_READ_AVG, DISK_IO_WRITE_AVG]; **/

        }


@Component({
    selector: 'app-charts',
    templateUrl: './charts.component.html',
    styleUrls: ['./charts.component.scss'],
    animations: [routerTransition()],
    providers:[BlueprismServices]
})
export class ChartsComponent implements OnInit {

    dataArray : any[] = [];
    private robot : string;
    private application: BlueprismModel;
    @Output()  applications: BlueprismModel[];
    public machine_name: string;
    errorMessage : "Invalid Data";
    item : any[];
    dateString : Date;
    device_name = new Set ([]);

    constructor(private blueprismService: BlueprismService, private service: BlueprismServices, private dataLoad: DataLoadService,
    private varModel: VarModel) {
    }

    ngOnInit(){
        this.loadApplications();
    }

    loadApplications(){

         this.blueprismService.getBlueprismData().subscribe(
            blue_applications => {

            this.varModel.PHYSICAL_MEMORY_UTIL_AVG = blue_applications['value'].map(blue_applications => blue_applications.PHYSICAL_MEMORY_UTIL_AVG);
            this.varModel.SERVING_DEVICE_NAME = blue_applications['value'].map(blue_applications => blue_applications.SERVING_DEVICE_NAME);
            this.varModel.CPU_UTILIZATION_AVG = blue_applications['value'].map(blue_applications => blue_applications.CPU_UTILIZATION_AVG);
            this.varModel.DISK_QUEUE_LENGTH_MAX = blue_applications['value'].map(blue_applications => blue_applications.DISK_QUEUE_LENGTH_MAX);

            this.varModel.USERNAME = blue_applications['value'].map(blue_applications => blue_applications.USERNAME);
            this.varModel.VIRTUAL_MEMORY_UTIL_AVG = blue_applications['value'].map(blue_applications => blue_applications.VIRTUAL_MEMORY_UTIL_AVG);
            this.varModel.NETWORK_READ_AVG = blue_applications['value'].map(blue_applications => blue_applications.NETWORK_READ_AVG);
            this.varModel.NETWORK_WRITE_AVG = blue_applications['value'].map(blue_applications => blue_applications.NETWORK_WRITE_AVG);
            this.varModel.HOUR_RUNNING_TOTAL = blue_applications['value'].map(blue_applications => blue_applications.HOUR_RUNNING_TOTAL);
            this.varModel.DISK_IO_READ_AVG = blue_applications['value'].map(blue_applications => blue_applications.DISK_IO_READ_AVG);
            this.varModel.DISK_IO_WRITE_AVG = blue_applications['value'].map(blue_applications => blue_applications.DISK_IO_WRITE_AVG);

            this.device_name = new Set(this.varModel.SERVING_DEVICE_NAME);
            console.log(this.device_name);
           /* console.log(cpu_util_avg);
            console.log(disk_queue_length);
            console.log(virtual_memory);
            console.log(network_write_avg);
            console.log(DISK_IO_READ_AVG); **/

            this.barChartData = [

                { data: this.varModel.CPU_UTILIZATION_AVG, label: 'Cpu Avg' },
                { data: this.varModel.PHYSICAL_MEMORY_UTIL_AVG, label: 'Memory%' },
                { data: this.varModel.DISK_QUEUE_LENGTH_MAX, label: 'DQL' },
                { data: this.varModel.VIRTUAL_MEMORY_UTIL_AVG, label: 'Virtual Memory' }
            ];

           /* this.doughnutChartData = [network_read_avg, network_write_avg, DISK_IO_READ_AVG, DISK_IO_WRITE_AVG]; **/

        }, // Bind to view
        err => {
          // Log errors if any
          console.log(err);
        }
        );
    }

    getElements(arr: any[]){
        console.log("Checking");
        for(var item in arr) {
            console.log(item);
           /* return this.x; **/
        }
    }

    // bar chart
    private barChartOptions: any = {
        scaleShowVerticalLines: false,
        responsive: true
    };

    private barChartLabels: string[] = [
    'Sunday',
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday'
    ];
    private barChartType: string = 'bar';
    private barChartLegend: boolean = true;

    private dataArr: any[] = [{data:[], label:''}];
    private barChartData: any[];

    // Doughnut
    private doughnutChartLabels: string[] = [
        'DQL',
        'UXI',
        'MEMORY',
        'NO OF CRASHES'

    ];
    private doughnutChartData: number[];
    private doughnutChartData: number[] = [350.9887, 450, 100, 90];


ngOnInit(){
        this.loadApplications();
    }


loadApplications(){

         this.blueprismService.getBlueprismData().subscribe(
            blue_applications => {

            this.varModel.PHYSICAL_MEMORY_UTIL_AVG = blue_applications['value'].map(blue_applications => blue_applications.PHYSICAL_MEMORY_UTIL_AVG);
            this.varModel.SERVING_DEVICE_NAME = blue_applications['value'].map(blue_applications => blue_applications.SERVING_DEVICE_NAME);
            this.varModel.CPU_UTILIZATION_AVG = blue_applications['value'].map(blue_applications => blue_applications.CPU_UTILIZATION_AVG);
            this.varModel.DISK_QUEUE_LENGTH_MAX = blue_applications['value'].map(blue_applications => blue_applications.DISK_QUEUE_LENGTH_MAX);

            this.varModel.USERNAME = blue_applications['value'].map(blue_applications => blue_applications.USERNAME);
            this.varModel.VIRTUAL_MEMORY_UTIL_AVG = blue_applications['value'].map(blue_applications => blue_applications.VIRTUAL_MEMORY_UTIL_AVG);
            this.varModel.NETWORK_READ_AVG = blue_applications['value'].map(blue_applications => blue_applications.NETWORK_READ_AVG);
            this.varModel.NETWORK_WRITE_AVG = blue_applications['value'].map(blue_applications => blue_applications.NETWORK_WRITE_AVG);
            this.varModel.HOUR_RUNNING_TOTAL = blue_applications['value'].map(blue_applications => blue_applications.HOUR_RUNNING_TOTAL);
            this.varModel.DISK_IO_READ_AVG = blue_applications['value'].map(blue_applications => blue_applications.DISK_IO_READ_AVG);
            this.varModel.DISK_IO_WRITE_AVG = blue_applications['value'].map(blue_applications => blue_applications.DISK_IO_WRITE_AVG);

            this.device_name = new Set(this.varModel.SERVING_DEVICE_NAME);
            console.log(this.device_name);
           /* console.log(cpu_util_avg);
            console.log(disk_queue_length);
            console.log(virtual_memory);
            console.log(network_write_avg);
            console.log(DISK_IO_READ_AVG); **/

            this.barChartData = [

                { data: this.varModel.CPU_UTILIZATION_AVG, label: 'Cpu Avg' },
                { data: this.varModel.PHYSICAL_MEMORY_UTIL_AVG, label: 'Memory%' },
                { data: this.varModel.DISK_QUEUE_LENGTH_MAX, label: 'DQL' },
                { data: this.varModel.VIRTUAL_MEMORY_UTIL_AVG, label: 'Virtual Memory' }
            ];

           /* this.doughnutChartData = [network_read_avg, network_write_avg, DISK_IO_READ_AVG, DISK_IO_WRITE_AVG]; **/

        }, // Bind to view
        err => {
          // Log errors if any
          console.log(err);
        }
        );
    }


getElements(arr: any[]){
        console.log("Checking");
        for(var item in arr) {
            console.log(item);
           /* return this.x; **/
        }
    }


props => {
  return React.createElement(SurveyQuestion, props);
}


export class SurveyQuestion extends SurveyElementBase<any, any> {
  private isNeedFocus = false;
  public static renderQuestionBody(
    creator: ISurveyCreator,
    question: Question
  ): JSX.Element {
    if (!question.visible) return null;
    var customWidget = question.customWidget;
    if (!customWidget) {
      return creator.createQuestionElement(question);
    }
    return <SurveyCustomWidget creator={creator} question={question} />;
  }
  private rootRef: React.RefObject<HTMLDivElement>;
  constructor(props: any) {
    super(props);
    this.rootRef = React.createRef();
  }
  protected getStateElement(): Base {
    return this.question;
  }
  protected get question(): Question {
    return this.props.element;
  }
  private get creator(): ISurveyCreator {
    return this.props.creator;
  }
  componentDidMount() {
    super.componentDidMount();
    if (!!this.question) {
      this.question["react"] = this;
    }
    this.doAfterRender();
  }
  componentWillUnmount() {
    super.componentWillUnmount();
    if (!!this.question) {
      this.question["react"] = null;
    }
    var el = this.rootRef.current;
    if (!!el) {
      el.removeAttribute("data-rendered");
    }
  }
  componentDidUpdate(prevProps: any, prevState: any) {
    super.componentDidUpdate(prevProps, prevState);
    this.doAfterRender();
  }
  private doAfterRender() {
    if (this.isNeedFocus) {
      this.question.clickTitleFunction();
      this.isNeedFocus = false;
    }
    if (this.question) {
      var el = this.rootRef.current;
      if (el && el.getAttribute("data-rendered") !== "r") {
        el.setAttribute("data-rendered", "r");
        el.setAttribute("name", this.question.name);
        if (this.question.afterRender) {
          this.question.afterRender(el);
        }
      }
    }
  }
  protected canRender(): boolean {
    return (
      super.canRender() &&
      !!this.question &&
      !!this.creator &&
      this.question.isVisible
    );
  }
  protected renderElement(): JSX.Element {
    var question = this.question;
    var cssClasses = question.cssClasses;
    var questionRender = this.renderQuestion();
    var header = this.renderHeader(question);
    var headerTop = question.hasTitleOnLeftTop ? header : null;
    var headerBottom = question.hasTitleOnBottom ? header : null;
    var descriptionUnderInput = question.hasDescriptionUnderInput
      ? this.renderDescription(cssClasses, true)
      : null;
    let questionRootClass = question.cssRoot;

    var comment =
      question && question.hasComment ? this.renderComment(cssClasses) : null;
    var errorsTop =
      this.creator.questionErrorLocation() === "top"
        ? this.renderErrors(cssClasses, "top")
        : null;
    var errorsBottom =
      this.creator.questionErrorLocation() === "bottom"
        ? this.renderErrors(cssClasses, "bottom")
        : null;
    let rootStyle: { [index: string]: any } = {};
    if (question.renderWidth) {
      rootStyle["width"] = question.renderWidth;
      rootStyle["flexGrow"] = 1;
      rootStyle["flexShrink"] = 1;
      rootStyle["flexBasis"] = question.renderWidth;
      rootStyle["minWidth"] = question.minWidth;
      rootStyle["maxWidth"] = question.maxWidth;
    }
    if (!!question.paddingLeft) rootStyle["paddingLeft"] = question.paddingLeft;
    if (!!question.paddingRight)
      rootStyle["paddingRight"] = question.paddingRight;

    var contentStyle = {
      display: !this.question.isCollapsed ? "block" : "none",
    };

    if (question.isReadOnly) {
      questionRootClass += " " + cssClasses.disabled;
    }

    return (
      <div
        ref={this.rootRef}
        id={question.id}
        className={questionRootClass}
        style={rootStyle}
        role={question.ariaRole}
        aria-labelledby={question.hasTitle ? question.ariaTitleId : null}
      >
        {headerTop}
        <div className={question.cssContent} style={contentStyle}>
          {errorsTop}
          {questionRender}
          {comment}
          {errorsBottom}
          {descriptionUnderInput}
        </div>
        {headerBottom}
      </div>
    );
  }
  protected wrapElement(element: JSX.Element): JSX.Element {
    const survey: ReactSurveyModel = this.question.survey as ReactSurveyModel;
    let wrapper: JSX.Element;
    if (survey) {
      wrapper = survey.wrapElement(element, this.question);
    }
    return wrapper ?? element;
  }
  protected renderQuestion(): JSX.Element {
    return SurveyQuestion.renderQuestionBody(this.creator, this.question);
  }
  protected renderTitle(cssClasses: any): JSX.Element {
    const titleComponent = ReactElementFactory.Instance.createElement(
      this.question.getTitleComponentName(),
      { element: this.question, cssClasses: this.question.cssClasses }
    );
    return (
      <h5
        className={this.question.cssTitle}
        aria-label={this.question.locTitle.renderedHtml}
        id={this.question.ariaTitleId}
        onClick={() => {
          this.question.toggleState();
        }}


export class SurveyElementErrors extends ReactSurveyElement {
  constructor(props: any) {
    super(props);
    this.state = this.getState();
  }
  protected get id(): string {
    return this.props.id;
  }
  protected get element(): SurveyElement {
    var element = this.props.element;
    return element instanceof SurveyElement ? element : null;
  }
  private get creator(): ISurveyCreator {
    return this.props.creator;
  }
  protected get location(): string {
    return this.props.location;
  }
  private getState(prevState: any = null) {
    return !prevState ? { error: 0 } : { error: prevState.error + 1 };
  }
  protected canRender(): boolean {
    return !!this.element && this.element.hasVisibleErrors;
  }
  protected renderElement(): JSX.Element {
    var errors = [];
    for (var i = 0; i < this.element.errors.length; i++) {
      var key = "error" + i;
      errors.push(
        this.creator.renderError(key, this.element.errors[i], this.cssClasses)
      );
    }
    var classes = this.cssClasses.error.root;

    if (this.location === "top") {
      classes += " " + this.cssClasses.error.locationTop;
    } else if (this.location === "bottom") {
      classes += " " + this.cssClasses.error.locationBottom;
    }

    return (
      <div role="alert" className={classes} id={this.id}>
        {errors}
      </div>
    );
  }
}


export class SurveyQuestionAndErrorsCell extends ReactSurveyElement {
  [index: string]: any;
  protected cellRef: React.RefObject<HTMLTableCellElement>;
  constructor(props: any) {
    super(props);
    this.cellRef = React.createRef();
  }
  protected getStateElement(): Base {
    return this.question;
  }
  protected get question(): Question {
    return this.getQuestion();
  }
  protected get creator(): ISurveyCreator {
    return this.props.creator;
  }
  protected getQuestion(): Question {
    return this.props.question;
  }
  componentDidMount() {
    super.componentDidMount();
    this.doAfterRender();
  }
  componentWillUnmount() {
    super.componentWillUnmount();
    if (this.question) {
      var el = this.cellRef.current;
      if (!!el) {
        el.removeAttribute("data-rendered");
      }
    }
  }
  componentDidUpdate(prevProps: any, prevState: any) {
    super.componentDidUpdate(prevProps, prevState);
    this.doAfterRender();
  }
  protected doAfterRender() {}
  protected getCellClass(): any {
    return null;
  }
  protected canRender(): boolean {
    return !!this.question;
  }
  protected renderElement(): JSX.Element {
    var errorsLocation = this.creator.questionErrorLocation();
    var errors = this.getShowErrors() ? (
      <SurveyElementErrors
        element={this.question}
        cssClasses={this.cssClasses}
        creator={this.creator}
        location={errorsLocation}
      />
    ) : null;
    var errorsTop = errorsLocation === "top" ? errors : null;
    var errorsBottom = errorsLocation === "bottom" ? errors : null;
    var renderedCell = this.renderQuestion();
    var style = this.getCellStyle();
    return (
      <td
        ref={this.cellRef}
        className={this.getCellClass() + " " + this.cssClasses.cell}
        title={this.getHeaderText()}
        style={style}
      >
        {errorsTop}
        {renderedCell}
        {errorsBottom}
      </td>
    );
  }
  protected getShowErrors(): boolean {
    return this.question.isVisible;
  }
  protected getCellStyle(): any {
    return null;
  }
  protected renderQuestion(): JSX.Element {
    return SurveyQuestion.renderQuestionBody(this.creator, this.question);
  }
  protected getHeaderText(): string {
    return "";
  }
}


export interface ISurveyCreator {
  createQuestionElement(question: Question): JSX.Element;
  renderError(key: string, error: SurveyError, cssClasses: any): JSX.Element;
  questionTitleLocation(): string;
  questionErrorLocation(): string;
}


public static renderQuestionBody(
    creator: ISurveyCreator,
    question: Question
  ): JSX.Element {
    if (!question.visible) return null;
    var customWidget = question.customWidget;
    if (!customWidget) {
      return creator.createQuestionElement(question);
    }
    return <SurveyCustomWidget creator={creator} question={question} />;
  }


protected getStateElement(): Base {
    return this.question;
  }


componentDidMount() {
    super.componentDidMount();
    if (!!this.question) {
      this.question["react"] = this;
    }
    this.doAfterRender();
  }


componentWillUnmount() {
    super.componentWillUnmount();
    if (!!this.question) {
      this.question["react"] = null;
    }
    var el = this.rootRef.current;
    if (!!el) {
      el.removeAttribute("data-rendered");
    }
  }


componentDidUpdate(prevProps: any, prevState: any) {
    super.componentDidUpdate(prevProps, prevState);
    this.doAfterRender();
  }


private doAfterRender() {
    if (this.isNeedFocus) {
      this.question.clickTitleFunction();
      this.isNeedFocus = false;
    }
    if (this.question) {
      var el = this.rootRef.current;
      if (el && el.getAttribute("data-rendered") !== "r") {
        el.setAttribute("data-rendered", "r");
        el.setAttribute("name", this.question.name);
        if (this.question.afterRender) {
          this.question.afterRender(el);
        }
      }
    }
  }


protected canRender(): boolean {
    return (
      super.canRender() &&
      !!this.question &&
      !!this.creator &&
      this.question.isVisible
    );
  }


protected renderElement(): JSX.Element {
    var question = this.question;
    var cssClasses = question.cssClasses;
    var questionRender = this.renderQuestion();
    var header = this.renderHeader(question);
    var headerTop = question.hasTitleOnLeftTop ? header : null;
    var headerBottom = question.hasTitleOnBottom ? header : null;
    var descriptionUnderInput = question.hasDescriptionUnderInput
      ? this.renderDescription(cssClasses, true)
      : null;
    let questionRootClass = question.cssRoot;

    var comment =
      question && question.hasComment ? this.renderComment(cssClasses) : null;
    var errorsTop =
      this.creator.questionErrorLocation() === "top"
        ? this.renderErrors(cssClasses, "top")
        : null;
    var errorsBottom =
      this.creator.questionErrorLocation() === "bottom"
        ? this.renderErrors(cssClasses, "bottom")
        : null;
    let rootStyle: { [index: string]: any } = {};
    if (question.renderWidth) {
      rootStyle["width"] = question.renderWidth;
      rootStyle["flexGrow"] = 1;
      rootStyle["flexShrink"] = 1;
      rootStyle["flexBasis"] = question.renderWidth;
      rootStyle["minWidth"] = question.minWidth;
      rootStyle["maxWidth"] = question.maxWidth;
    }
    if (!!question.paddingLeft) rootStyle["paddingLeft"] = question.paddingLeft;
    if (!!question.paddingRight)
      rootStyle["paddingRight"] = question.paddingRight;

    var contentStyle = {
      display: !this.question.isCollapsed ? "block" : "none",
    };

    if (question.isReadOnly) {
      questionRootClass += " " + cssClasses.disabled;
    }

    return (
      <div
        ref={this.rootRef}
        id={question.id}
        className={questionRootClass}
        style={rootStyle}
        role={question.ariaRole}
        aria-labelledby={question.hasTitle ? question.ariaTitleId : null}
      >
        {headerTop}
        <div className={question.cssContent} style={contentStyle}>
          {errorsTop}
          {questionRender}
          {comment}
          {errorsBottom}
          {descriptionUnderInput}
        </div>
        {headerBottom}
      </div>
    );
  }


protected wrapElement(element: JSX.Element): JSX.Element {
    const survey: ReactSurveyModel = this.question.survey as ReactSurveyModel;
    let wrapper: JSX.Element;
    if (survey) {
      wrapper = survey.wrapElement(element, this.question);
    }
    return wrapper ?? element;
  }


protected renderQuestion(): JSX.Element {
    return SurveyQuestion.renderQuestionBody(this.creator, this.question);
  }


protected renderTitle(cssClasses: any): JSX.Element {
    const titleComponent = ReactElementFactory.Instance.createElement(
      this.question.getTitleComponentName(),
      { element: this.question, cssClasses: this.question.cssClasses }
    );
    return (
      <h5
        className={this.question.cssTitle}
        aria-label={this.question.locTitle.renderedHtml}
        id={this.question.ariaTitleId}
        onClick={() => {
          this.question.toggleState();
        }}


private getState(prevState: any = null) {
    return !prevState ? { error: 0 } : { error: prevState.error + 1 };
  }


protected canRender(): boolean {
    return !!this.element && this.element.hasVisibleErrors;
  }


protected renderElement(): JSX.Element {
    var errors = [];
    for (var i = 0; i < this.element.errors.length; i++) {
      var key = "error" + i;
      errors.push(
        this.creator.renderError(key, this.element.errors[i], this.cssClasses)
      );
    }
    var classes = this.cssClasses.error.root;

    if (this.location === "top") {
      classes += " " + this.cssClasses.error.locationTop;
    } else if (this.location === "bottom") {
      classes += " " + this.cssClasses.error.locationBottom;
    }

    return (
      <div role="alert" className={classes} id={this.id}>
        {errors}
      </div>
    );
  }


protected getQuestion(): Question {
    return this.props.question;
  }


componentDidMount() {
    super.componentDidMount();
    this.doAfterRender();
  }


componentWillUnmount() {
    super.componentWillUnmount();
    if (this.question) {
      var el = this.cellRef.current;
      if (!!el) {
        el.removeAttribute("data-rendered");
      }
    }
  }


protected doAfterRender() {}


protected getCellClass(): any {
    return null;
  }


protected canRender(): boolean {
    return !!this.question;
  }


protected renderElement(): JSX.Element {
    var errorsLocation = this.creator.questionErrorLocation();
    var errors = this.getShowErrors() ? (
      <SurveyElementErrors
        element={this.question}
        cssClasses={this.cssClasses}
        creator={this.creator}
        location={errorsLocation}
      />
    ) : null;
    var errorsTop = errorsLocation === "top" ? errors : null;
    var errorsBottom = errorsLocation === "bottom" ? errors : null;
    var renderedCell = this.renderQuestion();
    var style = this.getCellStyle();
    return (
      <td
        ref={this.cellRef}
        className={this.getCellClass() + " " + this.cssClasses.cell}
        title={this.getHeaderText()}
        style={style}
      >
        {errorsTop}
        {renderedCell}
        {errorsBottom}
      </td>
    );
  }


protected getShowErrors(): boolean {
    return this.question.isVisible;
  }


protected getCellStyle(): any {
    return null;
  }


protected getHeaderText(): string {
    return "";
  }


e => ({ error: e })


export class CommandContext {
    public additionalArgs: Collection<string, any> = new Collection();
    public channel: TextBasedChannel | null = this.context.channel;
    public guild = this.context.guild;

    public constructor(public readonly context: CommandInteraction
    | ContextMenuInteraction
    | Interaction
    | Message
    | SelectMenuInteraction,
    public args: string[] = []) {}

    public async deferReply(): Promise<void> {
        if (this.isInteraction()) {
            return (this.context as CommandInteraction).deferReply();
        }
        return Promise.resolve(undefined);
    }

    public async reply(options: InteractionReplyOptions
    | MessageOptions
    | MessagePayload
    | string
    | { askDeletion?: { reference: string } }, autoedit?: boolean): Promise<Message> {
        if (this.isInteraction()) {
            if ((this.context as Interaction).isCommand() &&
            (this.context as CommandInteraction).replied &&
            !autoedit) throw new Error("Interaction is already replied.");
        }

        const context = this.context as CommandInteraction | Message;
        const rep = await this.send(
            options,
            this.isInteraction()
                ? (
                    context as Interaction).isCommand()
                    ? (context as CommandInteraction).replied || (context as CommandInteraction).deferred
                        ? "editReply"
                        : "reply"
                    : "reply"
                : "reply"
        ).catch(e => ({ error: e }));
        if (!rep || "error" in rep) {
            throw new Error(
                `Unable to reply context, because: ${rep ? (rep.error as Error).message : "Unknown"}`
            );
        }

        // @ts-expect-error-next-line
        return rep instanceof Message ? rep : new Message(this.context.client, rep);
    }

    public async send(options: InteractionReplyOptions
    | MessageOptions
    | MessagePayload
    | string
    | { askDeletion?: { reference: string } },
    type: MessageInteractionAction = "editReply"): Promise<Message> {
        const deletionBtn = new MessageActionRow()
            .addComponents(
                new MessageButton()
                    .setEmoji("🗑")
                    .setStyle("DANGER")
            );
        if ((options as { askDeletion?: { reference: string } }).askDeletion) {
            deletionBtn.components[0].setCustomId(
                Buffer.from(`${(options as { askDeletion: { reference: string } }).askDeletion.reference}_delete-msg`)
                    .toString("base64")
            );
            // eslint-disable-next-line @typescript-eslint/no-unused-expressions
            (options as InteractionReplyOptions).components
                ? (options as InteractionReplyOptions).components!.push(deletionBtn)
                : (options as InteractionReplyOptions).components = [deletionBtn];
        }
        if (this.isInteraction()) {
            (options as InteractionReplyOptions).fetchReply = true;
            const msg = await (this.context as CommandInteraction)[type](options as InteractionReplyOptions | MessagePayload | string) as Message;
            const channel = this.context.channel;
            const res = await channel!.messages.fetch(msg.id).catch(() => null);
            return res ?? msg;
        }
        if ((options as InteractionReplyOptions).ephemeral) {
            throw new Error("Cannot send ephemeral message in a non-interaction context.");
        }
        return this.context.channel!.send(options as MessageOptions | MessagePayload | string);
    }

    public isInteraction(): boolean {
        return this.context instanceof Interaction;
    }

    public isCommand(): boolean {
        return this.context instanceof CommandInteraction;
    }

    public isContextMenu(): boolean {
        return this.context instanceof ContextMenuInteraction;
    }

    public isMessageComponent(): boolean {
        return this.context instanceof MessageComponentInteraction;
    }

    public isButton(): boolean {
        return this.context instanceof ButtonInteraction;
    }

    public isSelectMenu(): boolean {
        return this.context instanceof SelectMenuInteraction;
    }

    public get mentions(): MessageMentions | null {
        return this.context instanceof Message ? this.context.mentions : null;
    }

    public get deferred(): boolean {
        return this.context instanceof Interaction
            ? (this.context as CommandInteraction).deferred
            : false;
    }

    public get options(): CommandInteraction["options"] | null {
        return this.context instanceof Interaction
            ? (this.context as CommandInteraction).options
            : null;
    }

    public get author(): User {
        return this.context instanceof Interaction
            ? this.context.user
            : this.context.author;
    }

    public get member(): GuildMember | null {
        return this.guild!.members.resolve(this.author.id);
    }
}


public async deferReply(): Promise<void> {
        if (this.isInteraction()) {
            return (this.context as CommandInteraction).deferReply();
        }
        return Promise.resolve(undefined);
    }


public async reply(options: InteractionReplyOptions
    | MessageOptions
    | MessagePayload
    | string
    | { askDeletion?: { reference: string } }, autoedit?: boolean): Promise<Message> {
        if (this.isInteraction()) {
            if ((this.context as Interaction).isCommand() &&
            (this.context as CommandInteraction).replied &&
            !autoedit) throw new Error("Interaction is already replied.");
        }

        const context = this.context as CommandInteraction | Message;
        const rep = await this.send(
            options,
            this.isInteraction()
                ? (
                    context as Interaction).isCommand()
                    ? (context as CommandInteraction).replied || (context as CommandInteraction).deferred
                        ? "editReply"
                        : "reply"
                    : "reply"
                : "reply"
        ).catch(e => ({ error: e }));
        if (!rep || "error" in rep) {
            throw new Error(
                `Unable to reply context, because: ${rep ? (rep.error as Error).message : "Unknown"}`
            );
        }

        // @ts-expect-error-next-line
        return rep instanceof Message ? rep : new Message(this.context.client, rep);
    }


public async send(options: InteractionReplyOptions
    | MessageOptions
    | MessagePayload
    | string
    | { askDeletion?: { reference: string } },
    type: MessageInteractionAction = "editReply"): Promise<Message> {
        const deletionBtn = new MessageActionRow()
            .addComponents(
                new MessageButton()
                    .setEmoji("🗑")
                    .setStyle("DANGER")
            );
        if ((options as { askDeletion?: { reference: string } }).askDeletion) {
            deletionBtn.components[0].setCustomId(
                Buffer.from(`${(options as { askDeletion: { reference: string } }).askDeletion.reference}_delete-msg`)
                    .toString("base64")
            );
            // eslint-disable-next-line @typescript-eslint/no-unused-expressions
            (options as InteractionReplyOptions).components
                ? (options as InteractionReplyOptions).components!.push(deletionBtn)
                : (options as InteractionReplyOptions).components = [deletionBtn];
        }
        if (this.isInteraction()) {
            (options as InteractionReplyOptions).fetchReply = true;
            const msg = await (this.context as CommandInteraction)[type](options as InteractionReplyOptions | MessagePayload | string) as Message;
            const channel = this.context.channel;
            const res = await channel!.messages.fetch(msg.id).catch(() => null);
            return res ?? msg;
        }
        if ((options as InteractionReplyOptions).ephemeral) {
            throw new Error("Cannot send ephemeral message in a non-interaction context.");
        }
        return this.context.channel!.send(options as MessageOptions | MessagePayload | string);
    }


public isInteraction(): boolean {
        return this.context instanceof Interaction;
    }


public isCommand(): boolean {
        return this.context instanceof CommandInteraction;
    }


public isContextMenu(): boolean {
        return this.context instanceof ContextMenuInteraction;
    }


public isMessageComponent(): boolean {
        return this.context instanceof MessageComponentInteraction;
    }


public isButton(): boolean {
        return this.context instanceof ButtonInteraction;
    }


public isSelectMenu(): boolean {
        return this.context instanceof SelectMenuInteraction;
    }


(params:Params)=>{
            this.id =params['id'];
        }


@Component({
    selector: 'producto',
    templateUrl: './producto.component.html',
    providers: [ProductoService]
})
export class ProductoComponent  {
    public str="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed    viverra velit sed felis aliquet viverra. Nullam et tortor viverra    magna consequat fringilla. Duis auctor finibus lectus non ornare.    Donec posuere massa egestas volutpat interdum. Duis vitae    sapien ac tortor dapibus accumsan id sed lacus. Donec    elementum porta commodo. Ut volutpat, dolor aliquet    pellentesque sodales, lorem lacus posuere est, vitae maximus leo    magna at mauris. Proin id maximus enim. Cras eu ante id nisl    commodo vehicula et vel lectus. Nullam id consectetur erat.    Mauris vel odio ligula. Sed elementum eu eros et convallis. Proin    non massa sed tellus eleifend gravida. Praesent ut nisi dui. Nunc    velit magna, imperdiet a sollicitudin pulvinar, convallis id sem"
    public producto:Producto;
    public id:String;
    public media=2;
    public comentarios:Array<Comentario>;
    constructor( private _router:Router,
        private _route: ActivatedRoute,){
        this.producto=new Producto(1,"titulo",this.str,"../../assets/icons/carro.png","../../assets/icons/carro.png",5.52);
        this.comentarios=[new Comentario(1,1,2,"Muy bueno",5),new Comentario(2,1,1,"Muy malo",1)];
    }
    ngOnInit(){
        this._route.params.forEach((params:Params)=>{
            this.id =params['id'];
        });
        //this._empleadoService= new EmpleadoService();
        //this.trabajadores= this._empleadoService.getEmpleados();
    }
}


ngOnInit(){
        this._route.params.forEach((params:Params)=>{
            this.id =params['id'];
        });
        //this._empleadoService= new EmpleadoService();
        //this.trabajadores= this._empleadoService.getEmpleados();
    }


export function MoviesListItem({ movie }: MoviesListItemProps) {
  const [showDescription, setShowDescription] = useState(false);
  return (
    <li
      onClick={() => setShowDescription((prev) => !prev)}


(prev) => !prev


type MoviesListItemProps = {
  movie: Movie;
};


()=> {
        mockIot = new AWS.Iot();
        mockS3 = new AWS.S3();

        // SSM mock
        const mockSSM = new AWS.SSM();
        mockSSM.getParameter = jest.fn().mockImplementationOnce(()=> {
            return {
              promise: () : AWS.SSM.Types.GetParameterResult => null
            };
        });

        const mockClientIdEnforcementPolicyStepProcessor = new ClientIdEnforcementPolicyStepProcessor(() => mockIot, 'region', 'accountId');
        const mockCreateDeviceCertificateStepProcessor = new CreateDeviceCertificateStepProcessor(() => mockIot, () => mockSSM, 365);
        const mockRegisterDeviceCertificateWithoutCAStepProcessor = new RegisterDeviceCertificateWithoutCAStepProcessor(() => mockIot);

        instance = new ThingsService(() => mockIot, () => mockS3, mockClientIdEnforcementPolicyStepProcessor, mockCreateDeviceCertificateStepProcessor, mockRegisterDeviceCertificateWithoutCAStepProcessor,
        's3rolearn', 'templateBucket',  'teplatePrefix', 'templateSuffix', 'bulkRequestBukcet', 'bulkRequestPrefix',
        false, false);
    }


()=> {
            return {
              promise: () : AWS.SSM.Types.GetParameterResult => null
            };
        }


() : AWS.SSM.Types.GetParameterResult => null


() => mockIot


() => mockSSM


() => mockS3


()=> {
            return {
            promise: () : AWS.S3.Types.GetObjectOutput => s3GetObjectResponse
            };
        }


() : AWS.S3.Types.GetObjectOutput => s3GetObjectResponse


()=> {
            return {
            promise: () : AWS.Iot.Types.RegisterThingResponse => registerThingResponse
            };
        }


() : AWS.Iot.Types.RegisterThingResponse => registerThingResponse


async () => {

        const listThingPrincipalsResponse:AWS.Iot.Types.ListThingPrincipalsResponse = {
            principals: []
        };

        mockIot.listThingPrincipals = jest.fn().mockImplementationOnce(()=> {
            return {
              promise: () : AWS.Iot.Types.ListThingPrincipalsResponse => listThingPrincipalsResponse
            };
        });

        let deleteThingResponseCalls = 0;
        mockIot.deleteThing = jest.fn().mockImplementationOnce(()=> {
            deleteThingResponseCalls++;
            return {
              promise: () : AWS.Iot.Types.DeleteThingResponse => null
            };
        });

        let deleteCertificateCalls = 0;
        mockIot.deleteCertificate = jest.fn().mockImplementationOnce(()=> {
            deleteCertificateCalls++;
            return {
              promise: () : {} => null
            };
        });

        // now do the service call
        await instance.deleteThing('unitTestThing');

        expect(deleteThingResponseCalls).toEqual(1);

        expect(deleteCertificateCalls).toEqual(0);
    }


()=> {
            return {
              promise: () : AWS.Iot.Types.ListThingPrincipalsResponse => listThingPrincipalsResponse
            };
        }


() : AWS.Iot.Types.ListThingPrincipalsResponse => listThingPrincipalsResponse


()=> {
            deleteThingResponseCalls++;
            return {
              promise: () : AWS.Iot.Types.DeleteThingResponse => null
            };
        }


() : AWS.Iot.Types.DeleteThingResponse => null


()=> {
            deleteCertificateCalls++;
            return {
              promise: () : {} => null
            };
        }


() : {} => null


({
  children,
  error,
  className,
  centered,
}: {
  children: React.ReactNode;
  centered?: boolean;
  error?: boolean;
  className?: string;
}): JSX.Element => {
  const classes = [
    "tnic-message",
    error && "error",
    centered !== false && "centered",
    className,
  ].filter(Boolean);

  return (

{children}


({ api, namespace, name, timeRange }: ErrorsGraphProps): JSX.Element => {
  const [errors, setErrors] = useState<any[]>([])
  const [errorsQuery, setErrorsQuery] = useState<string>('')
  const [errorsLabels, setErrorsLabels] = useState<string[]>([])
  const [errorsLoading, setErrorsLoading] = useState<boolean>(true)

  useEffect(() => {
    const now = Date.now()
    const start = Math.floor((now - timeRange) / 1000)
    const end = Math.floor(now / 1000)

    setErrorsLoading(true)
    api.getREDErrors({ namespace, name, start, end })
      .then((r: QueryRange) => {
        let data: any[] = []
        r.values.forEach((v: number[], i: number) => {
          v.forEach((v: number, j: number) => {
            if (j === 0) {
              data[i] = { t: v }
            } else {
              data[i][j - 1] = 100 * v
            }
          })
        })
        setErrorsLabels(r.labels)
        setErrorsQuery(r.query)
        setErrors(data)
      }).finally(() => setErrorsLoading(false))

  }, [api, namespace, name, timeRange])

  const ErrorsTooltip = ({ payload }: TooltipProps<number, number>): JSX.Element => {
    const style = {
      padding: 10,
      paddingTop: 5,
      paddingBottom: 5,
      backgroundColor: 'white',
      border: '1px solid #666',
      borderRadius: 3
    }
    if (payload !== undefined && payload?.length > 0) {
      return (

          Date: {dateFormatterFull(payload[0].payload.t)}

          {Object.keys(payload[0].payload).filter((k) => k !== 't').map((k: string, i: number) => (

              {errorsLabels[i] !== '{}' ? `${errorsLabels[i]}:` : ''}
              {(payload[0].payload[k]).toFixed(2)}%


() => {
    const now = Date.now()
    const start = Math.floor((now - timeRange) / 1000)
    const end = Math.floor(now / 1000)

    setErrorsLoading(true)
    api.getREDErrors({ namespace, name, start, end })
      .then((r: QueryRange) => {
        let data: any[] = []
        r.values.forEach((v: number[], i: number) => {
          v.forEach((v: number, j: number) => {
            if (j === 0) {
              data[i] = { t: v }
            } else {
              data[i][j - 1] = 100 * v
            }
          })
        })
        setErrorsLabels(r.labels)
        setErrorsQuery(r.query)
        setErrors(data)
      }).finally(() => setErrorsLoading(false))

  }


(r: QueryRange) => {
        let data: any[] = []
        r.values.forEach((v: number[], i: number) => {
          v.forEach((v: number, j: number) => {
            if (j === 0) {
              data[i] = { t: v }
            } else {
              data[i][j - 1] = 100 * v
            }
          })
        })
        setErrorsLabels(r.labels)
        setErrorsQuery(r.query)
        setErrors(data)
      }


(v: number[], i: number) => {
          v.forEach((v: number, j: number) => {
            if (j === 0) {
              data[i] = { t: v }
            } else {
              data[i][j - 1] = 100 * v
            }
          })
        }


(v: number, j: number) => {
            if (j === 0) {
              data[i] = { t: v }
            } else {
              data[i][j - 1] = 100 * v
            }
          }


() => setErrorsLoading(false)


({ payload }: TooltipProps<number, number>): JSX.Element => {
    const style = {
      padding: 10,
      paddingTop: 5,
      paddingBottom: 5,
      backgroundColor: 'white',
      border: '1px solid #666',
      borderRadius: 3
    }
    if (payload !== undefined && payload?.length > 0) {
      return (

          Date: {dateFormatterFull(payload[0].payload.t)}

          {Object.keys(payload[0].payload).filter((k) => k !== 't').map((k: string, i: number) => (

              {errorsLabels[i] !== '{}' ? `${errorsLabels[i]}:` : ''}
              {(payload[0].payload[k]).toFixed(2)}%


(k) => k !== 't'


(k: string, i: number) => (
            <div key={i}>
              {errorsLabels[i] !== '{}' ? `${errorsLabels[i]}:` : ''}


(k: string) => k !== 't'


(k: string, i: number) => {
              return <Area
                key={k}
                type="monotone"
                connectNulls={false}
                animationDuration={250}
                dataKey={k}
                stackId={1}
                strokeWidth={0}
                fill={`#${reds[i]}`}


interface ErrorsGraphProps {
  api: ObjectivesApi
  namespace: string
  name: string
  timeRange: number
}


dateFormatter(timeRange)


export function dvmAddressToAccountId(address: string | null | undefined): AccountId {
  if (!address) {
    return registry.createType('AccountId', '');
  }

  // eslint-disable-next-line no-magic-numbers
  const data = new Uint8Array(32);

  data.set(stringToU8a('dvm:'));
  // eslint-disable-next-line no-magic-numbers
  data.set(hexToU8a(address), 11);
  // eslint-disable-next-line no-bitwise
  const checksum = data.reduce((pre: number, current: number): number => pre ^ current);

  // eslint-disable-next-line no-magic-numbers
  data.set(numberToU8a(checksum), 31);
  const accountId = registry.createType<AccountId>('AccountId', data);

  return accountId;
}


export function convertToSS58(text: string, prefix: SS58Prefix, isShort = false): string {
  if (!text) {
    return '';
  }

  try {
    let address = encodeAddress(text, prefix);
    const length = 8;

    if (isShort) {
      address = address.substr(0, length) + '...' + address.substr(address.length - length, length);
    }

    return address;
  } catch (error) {
    return '';
  }
}


export function convertToDvm(address: string): string {
  if (!address) {
    return '';
  }

  return u8aToHex(decodeAddress(address));
}


export function canConvertToEth(address: string): boolean {
  return !!convertToEth(address);
}


export function convertToEth(address: string): string | null {
  if (!address) {
    return '';
  }

  const startAt = 2;
  const result = u8aToHex(decodeAddress(address)).slice(startAt);
  const PREFIX = '64766d3a00000000000000';

  // eslint-disable-next-line no-magic-numbers
  return result.startsWith(PREFIX) ? '0x' + result.slice(-42, -2) : null;
}


(pre: number, current: number): number => pre ^ current


(AWS: any) => {
  if (AWS.ApiGatewayManagementApi === undefined) {
    const { Service, apiLoader } = AWS;

    apiLoader.services.apigatewaymanagementapi = {};
    AWS.ApiGatewayManagementApi = Service.defineService(
      "apigatewaymanagementapi",
      ["2018-11-29"]
    );
    Object.defineProperty(
      apiLoader.services.apigatewaymanagementapi,
      "2018-11-29",
      {
        get: function get() {
          return model;
        },
        enumerable: true,
        configurable: true
      }
    );
  }
}


() => {
  let component: PostViewComponent;
  let fixture: ComponentFixture<PostViewComponent>;

  const testUser: User = {
    id: 1,
    firstName: 'first',
    lastName: 'last',
    email: 'e@mail',
    phoneNumber: undefined,
    profilePictureUrl: null,
    status: undefined,
    birthDate: new Date(2010, 12),
    followees: [],
    followers: []
  };

  const testComment: Comment = {
    id: 1,
    userEmail: 'e@email.com',
    content: 'comment content',
    postId: 1,
    createdAt: undefined
  };

  const testPost: Post = {
    id: 1,
    content: 'string',
    userEmail: 'e@mail',
    pictureUrl: undefined,
    createdAt: new Date(2020, 12),
    likedByUserIds: [],
    comments: [],
    liked: false
  };

  const fakeHTTPClient = { };
  const fakeOktaAuth = { getAccessToken(): void {} };
  beforeEach(async () => {
    const mockPostService = {
      delete(id: number): void {}
    };

    await TestBed.configureTestingModule({
      imports: [HttpClientModule],
      declarations: [ PostViewComponent ],
      providers: [
        {provide: PostService, useValue: mockPostService},
        {provide: ActivatedRoute, useValue: {}},
        { provide: HttpClientModule, useValue: fakeHTTPClient},
        { provide: OktaAuthService, useValue: fakeOktaAuth}

      ]
    })
    .compileComponents();
    fixture = TestBed.createComponent(PostViewComponent);
    component = new PostViewComponent(TestBed.inject(ActivatedRoute), TestBed.inject(PostService), TestBed.inject(ProfileService));
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
    expect(component.comments).toBeNull();
    expect(component.userEmail).toBe('');
  });

  it('should delete a post on deletePost()', () => {
    spyOn(component.postService, 'delete');
    component.deletePost(testPost);
    expect(component.post).toBeNull();
    expect(component.postService.delete).toHaveBeenCalled();
  });
}


async () => {
    const mockPostService = {
      delete(id: number): void {}
    };

    await TestBed.configureTestingModule({
      imports: [HttpClientModule],
      declarations: [ PostViewComponent ],
      providers: [
        {provide: PostService, useValue: mockPostService},
        {provide: ActivatedRoute, useValue: {}},
        { provide: HttpClientModule, useValue: fakeHTTPClient},
        { provide: OktaAuthService, useValue: fakeOktaAuth}

      ]
    })
    .compileComponents();
    fixture = TestBed.createComponent(PostViewComponent);
    component = new PostViewComponent(TestBed.inject(ActivatedRoute), TestBed.inject(PostService), TestBed.inject(ProfileService));
    fixture.detectChanges();
  }


() => {
    expect(component).toBeTruthy();
    expect(component.comments).toBeNull();
    expect(component.userEmail).toBe('');
  }


() => {
    spyOn(component.postService, 'delete');
    component.deletePost(testPost);
    expect(component.post).toBeNull();
    expect(component.postService.delete).toHaveBeenCalled();
  }


getAccessToken(): void {}


delete(id: number): void {}


(result) => {
            this.closeResult = `Closed with: ${result}`;
        }


(reason) => {
            this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
        }


data => {
            this.result = data['_body'];

            const jo = JSON.parse(this.result);
            const obj = Array.of(jo.data);
            this.jsonObj = obj[0];
            for (let index = 0; index < this.jsonObj.length; index++) {
                this.items.push(this.jsonObj[index]);
            }

        }


ngOnInit() {
        this.getAdressess();
        // this.autoMaps();
        // this.map = this.createMap();
        // this.addMapEventListeners();

        this.latGlobal = '33.888077';
        this.lngGlobal = '8.888077';

           const mapProp = {
            center: new google.maps.LatLng(this.latGlobal, this.lngGlobal),
            zoom: 15,
            mapTypeId: google.maps.MapTypeId.ROADMAP
          };
          this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
    }


ngAfterViewInit() {
    }


open(content) {
        this.modalService.open(content, { size: 'lg' }).result.then((result) => {
            this.closeResult = `Closed with: ${result}`;
        }, (reason) => {
            this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
        });
    }


openAddModal(content) {
        this.list = [
            '25063551',
            '25697304',
            '11111111'
          ];

        this.modalService.open(content, { size: 'lg' }).result.then((result) => {
            this.closeResult = `Closed with: ${result}`;
        }, (reason) => {
            this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
        });

        this.searchPlaces();
    }


private getDismissReason(reason: any): string {
        if (reason === ModalDismissReasons.ESC) {
            return 'by pressing ESC';
        } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
            return 'by clicking on a backdrop';
        } else {
            return  `with: ${reason}`;
        }
    }


getAdressess() {
        this.jsonObj = null;
        this.items = [];
        this.tservice.getAdresses().subscribe(data => {
            this.result = data['_body'];

            const jo = JSON.parse(this.result);
            const obj = Array.of(jo.data);
            this.jsonObj = obj[0];
            for (let index = 0; index < this.jsonObj.length; index++) {
                this.items.push(this.jsonObj[index]);
            }

        });
    }


editAdresse(adresse) {
        this.obj = adresse;
        this.objAdresse.updateday = this.obj.updateday;
        this.objAdresse.geolocAdr = this.obj.geolocAdr;
        this.objAdresse.labelAdr = this.obj.labelAdr;
        this.objAdresse.typeAdr = this.obj.typeAdr;
        this.objAdresse.cityAdr = this.obj.cityAdr;
        this.objAdresse.deletedbyUser = this.obj.deletedbyUser;
        this.objAdresse.createdday = this.obj.createdday;
        this.objAdresse.createdby = this.obj.createdby;
        this.objAdresse.updateby = this.obj.updateby;
        this.objAdresse.deletedbyDriver = this.obj.deletedbyDriver;
        this.objAdresse.createdday = this.obj.createdday;
        this.objAdresse.sharedtoAdr = this.obj.sharedtoAdr;
        this.objAdresse.contactAdr = this.obj.contactAdr;
        this.objAdresse.mobileAdr = this.obj.mobileAdr;
        this.objAdresse.idAdress = this.obj.idAdress;
        this.objAdresse.userAdr = this.obj.userAdr;
    }


autoMaps() {
        // const el: HTMLInputElement = this.elementRef.nativeElement.querySelector('#searchTextFiel');
        const searchTextFiel = document.getElementById('inputNewNomAdresse');
        const autocomplete = new google.maps.places.Autocomplete(searchTextFiel as HTMLInputElement);
        console.log(searchTextFiel);
        google.maps.event.addListener(autocomplete, 'place_changed', function () {
            console.log(autocomplete);
            const placee = autocomplete.getPlace();
            console.log(placee.name);
            console.log(placee.geometry.location.lat());
            console.log(placee.geometry.location.lng());
            let address = '';
              if (placee.address_components) {
                address = [
                  (placee.address_components[0] && placee.address_components[0].short_name || ''),
                  (placee.address_components[1] && placee.address_components[1].short_name || ''),
                  (placee.address_components[2] && placee.address_components[2].short_name || '')
                ].join(' ');
              }
              console.log(address);
        });
      }


searchPlaces() {

        //$('#idstatmap').hide();
        this.input = document.getElementById('inputNewNomAdresse');
        const searchBox = new google.maps.places.SearchBox(this.input);
        searchBox.addListener('places_changed', function() {
           const places = searchBox.getPlaces();
           console.log(places[0].geometry.location.lat());
           console.log(places[0].geometry.location.lng());
           this.latGlobal = places[0].geometry.location.lat();
           this.lngGlobal = places[0].geometry.location.lng();
           /* (<HTMLInputElement>document.getElementById('inputNewCityAdresse')).value = places[0].address_components[2].long_name; */
           let address = '';
           if (places[0].address_components) {
             address = [
               (places[0].address_components[0] && places[0].address_components[0].long_name || ''),
               (places[0].address_components[1] && places[0].address_components[1].long_name || ''),
               (places[0].address_components[2] && places[0].address_components[2].long_name || ''),
               (places[0].address_components[3] && places[0].address_components[3].long_name || '')
             ].join(' ');
           }
           console.log(address);

          if (places.length === 0) {
            return;
          }

          this.hide = true;
          console.log(this.hide);
          $('#idstatmap').show();
       });

    }


Selected(item: SelectedAutocompleteItem) {
        console.log(item);
    }


showMarker(){
        this.hideMarker();
        this.Marker =  new google.maps.Marker({
          map : this.map,
          animation : google.maps.Animation.BOUNCE,
          position : this.map.getCenter(),
          icon : 'src/assets/imgs/bg_pin.png'
        });
          this.Marker.setAnimation(google.maps.Animation.BOUNCE);
          this.markerLocation();
        // let markerlocation = new google.maps.LatLng();
        // markerlocation = this.Marker.getPosition();
          //this.updateLocation(this.adrPosition.lat().toString(),this.adrPosition.lng().toString())
        }


markerLocation() {
        let markerlocation = new google.maps.LatLng();
        markerlocation = this.Marker.getPosition();
        this.adrPosition = markerlocation;
        this.latGlobal = (this.adrPosition.lat()).toString();
         this.lngGlobal = (this.adrPosition.lng()).toString();
        return (markerlocation);
      }


hideMarker(){
        if(this.Marker){
          this.Marker.setMap(null);
        }
      }


export class DataValidator<T = any> {
  private readonly logger: Logger;
  private readonly statsD: StatsD;
  private readonly schema: joi.Schema;

  public constructor(logger: Logger, statsD: StatsD, schema: joi.Schema) {
    this.schema = schema;
    this.statsD = statsD;
    this.logger = logger;
  }

  public validate(data: unknown): T {
    const {error, value} = joi.validate(data, this.schema);
    if (error) {
      this.logger.error({
        data:  data,
        error: error,
      }, 'Data Validation Error');

      this.statsD.increment('data_validation_error');

      throw error;
    }

    return value as T;
  }
}


public validate(data: unknown): T {
    const {error, value} = joi.validate(data, this.schema);
    if (error) {
      this.logger.error({
        data:  data,
        error: error,
      }, 'Data Validation Error');

      this.statsD.increment('data_validation_error');

      throw error;
    }

    return value as T;
  }


export default function passwordsDontMatch(text: Text): string {
    return text.form.fieldError.passwordsDontMatch;
}


async () => instance as any


async (recipient, amount) =>
      instance['mint(address,uint256)'](recipient, amount)


async (recipient, amount) =>
      instance['burn(address,uint256)'](recipient, amount)


// type MainDropdownProps = {
// } & React.HTMLAttributes<HTMLDivElement>;
export function MainDropdown() {
  return (

      <TooltipDrawer
        className={styles.dropdown}
        tooltipClass={styles.menu}
        placeholder=""
        clickOutside
        PlaceholderComponent={() => (

            <Icon className={classNames(styles.icon)} of="more" />

        )}


function Line({ title, of }: { title: string; of: string }) {
  return (

{title}

      <Icon of={of} className={styles.key} />

  );
}


function MenuBlock({ title, children }: { title?: string; children?: ReactNode }) {
  return (

{title}

      {children}

  );
}


classNames(hoverable, styles


classNames(styles