# API Reference

## @tekdi/react-quml-player

Complete API documentation for all components, types, and utilities.

## Components

### QumlPlayer

The main component for rendering QUML assessments.

#### Props

```typescript
interface QumlPlayerProps {
  questionSetId: string;
  config: QumlConfig;
  onPlayerStateChange?: (state: PlayerState) => void;
  onComplete?: (results: AssessmentResults) => void;
  onRestart?: () => void;
  onExit?: () => void;
  className?: string;
}
```

##### Parameters

| Prop                  | Type                                   | Required | Description                                                  |
| --------------------- | -------------------------------------- | -------- | ------------------------------------------------------------ |
| `questionSetId`       | `string`                               | ✅       | Unique identifier for the question set to load               |
| `config`              | `QumlConfig`                           | ✅       | Configuration object for API, telemetry, and player settings |
| `onPlayerStateChange` | `(state: PlayerState) => void`         | ❌       | Callback fired when player state changes                     |
| `onComplete`          | `(results: AssessmentResults) => void` | ❌       | Callback fired when assessment is completed                  |
| `onRestart`           | `() => void`                           | ❌       | Callback fired when user restarts the assessment             |
| `onExit`              | `() => void`                           | ❌       | Callback fired when user exits the assessment                |
| `className`           | `string`                               | ❌       | Additional CSS classes to apply to the player container      |

#### Example

```typescript
<QumlPlayer
  questionSetId="assessment-123"
  config={qumlConfig}
  onComplete={(results) => console.log("Completed:", results)}
  onExit={() => navigate("/dashboard")}
  className="my-custom-player"
/>
```

### QumlPlayerWithOverview

Extended version of QumlPlayer with built-in question overview functionality.

#### Props

Same as `QumlPlayer` with additional options:

```typescript
interface QumlPlayerWithOverviewProps extends QumlPlayerProps {
  showOverviewByDefault?: boolean;
  allowOverviewNavigation?: boolean;
}
```

### Question Type Renderers

Individual components for rendering specific question types.

#### MCQRenderer

Renders Multiple Choice Questions (single select).

```typescript
interface MCQRendererProps {
  question: Question;
  response?: QuestionResponse;
  onResponse: (response: ResponseData) => void;
  showHints?: boolean;
  showSolutions?: boolean;
}
```

#### MMCQRenderer

Renders Multiple Choice Questions (multi-select).

```typescript
interface MMCQRendererProps {
  question: Question;
  response?: QuestionResponse;
  onResponse: (response: ResponseData) => void;
  showHints?: boolean;
  showSolutions?: boolean;
}
```

#### SARenderer

Renders Short Answer questions.

```typescript
interface SARendererProps {
  question: Question;
  response?: QuestionResponse;
  onResponse: (response: ResponseData) => void;
  allowFileUpload?: boolean;
  maxLength?: number;
}
```

#### LARenderer

Renders Long Answer questions.

```typescript
interface LARendererProps {
  question: Question;
  response?: QuestionResponse;
  onResponse: (response: ResponseData) => void;
  allowFileUpload?: boolean;
  minLength?: number;
  maxLength?: number;
}
```

#### MTFRenderer

Renders Match the Following questions with drag-and-drop.

```typescript
interface MTFRendererProps {
  question: Question;
  response?: QuestionResponse;
  onResponse: (response: ResponseData) => void;
  allowPartialCredit?: boolean;
}
```

#### ASQRenderer

Renders Arrange Sequence Question questions.

```typescript
interface ASQRendererProps {
  question: Question;
  response?: QuestionResponse;
  onResponse: (response: ResponseData) => void;
  showDetailedFeedback?: boolean;
}
```

## Configuration Types

### QumlConfig

Main configuration object for the QUML Player.

```typescript
interface QumlConfig {
  apiConfig: ApiConfig;
  telemetryConfig: TelemetryConfig;
  questionSetConfig?: QuestionSetConfig;
}
```

### ApiConfig

Configuration for API endpoints and authentication.

```typescript
interface ApiConfig {
  host: string;
  endpoint: string;
  headers?: Record<string, string>;
  timeout?: number;
  retryAttempts?: number;
}
```

| Property        | Type                     | Required | Default | Description                                  |
| --------------- | ------------------------ | -------- | ------- | -------------------------------------------- |
| `host`          | `string`                 | ✅       | -       | Base URL for the API server                  |
| `endpoint`      | `string`                 | ✅       | -       | API endpoint path for question data          |
| `headers`       | `Record<string, string>` | ❌       | `{}`    | Additional HTTP headers                      |
| `timeout`       | `number`                 | ❌       | `30000` | Request timeout in milliseconds              |
| `retryAttempts` | `number`                 | ❌       | `3`     | Number of retry attempts for failed requests |

### TelemetryConfig

Configuration for telemetry and analytics.

```typescript
interface TelemetryConfig {
  pdata: {
    id: string;
    ver: string;
    pid: string;
  };
  env: string;
  channel: string;
  uid?: string;
  sid?: string;
  did?: string;
  tags?: string[];
  cdata?: Array<{
    id: string;
    type: string;
  }>;
}
```

| Property    | Type                                | Required | Description                                  |
| ----------- | ----------------------------------- | -------- | -------------------------------------------- |
| `pdata.id`  | `string`                            | ✅       | Producer application identifier              |
| `pdata.ver` | `string`                            | ✅       | Producer application version                 |
| `pdata.pid` | `string`                            | ✅       | Producer ID (usually the app name)           |
| `env`       | `string`                            | ✅       | Environment (e.g., 'dev', 'staging', 'prod') |
| `channel`   | `string`                            | ✅       | Channel identifier                           |
| `uid`       | `string`                            | ❌       | User identifier                              |
| `sid`       | `string`                            | ❌       | Session identifier                           |
| `did`       | `string`                            | ❌       | Device identifier                            |
| `tags`      | `string[]`                          | ❌       | Additional tags for classification           |
| `cdata`     | `Array<{id: string; type: string}>` | ❌       | Correlation data                             |

### QuestionSetConfig

Optional configuration for question set behavior.

```typescript
interface QuestionSetConfig {
  showTimer?: boolean;
  showProgress?: boolean;
  randomizeQuestions?: boolean;
  maxQuestions?: number;
  showHints?: boolean;
  showSolutions?: boolean;
  enableReview?: boolean;
  autoSubmit?: boolean;
}
```

| Property             | Type      | Default     | Description                       |
| -------------------- | --------- | ----------- | --------------------------------- |
| `showTimer`          | `boolean` | `true`      | Display question/assessment timer |
| `showProgress`       | `boolean` | `true`      | Show progress bar                 |
| `randomizeQuestions` | `boolean` | `false`     | Randomize question order          |
| `maxQuestions`       | `number`  | `undefined` | Limit number of questions         |
| `showHints`          | `boolean` | `true`      | Show question hints               |

### Section-Level Configuration

#### Skip Configuration

The `allowSkip` property is configured at the **section level** within the QuestionSet structure:

```typescript
interface QuestionSet {
  allowSkip?: boolean; // Allow/disallow skipping questions in this section
  // ... other properties
}
```

| `showSolutions` | `boolean` | `false` | Show solutions during assessment |
| `enableReview` | `boolean` | `true` | Allow reviewing answers |
| `autoSubmit` | `boolean` | `false` | Auto-submit when time expires |

## Data Types

### Question

Represents a single question in the assessment.

```typescript
interface Question {
  identifier: string;
  name: string;
  body: string;
  qType: QuestionType;
  maxScore: number;
  timeLimit?: number;
  options?: Option[];
  correctAnswers?: any[];
  hints?: string[];
  solutions?: Solution[];
  media?: MediaElement[];
  interactions?: Interaction[];
  responseDeclaration?: ResponseDeclaration;
  primaryCategory?: string;
  mimeType?: string;
  showHints?: boolean;
  showSolutions?: boolean;
}
```

### QuestionType

Supported question types.

```typescript
type QuestionType = "MCQ" | "MMCQ" | "SA" | "LA" | "MTF" | "ASQ";
```

### Option

Represents an option in multiple choice questions.

```typescript
interface Option {
  identifier: string;
  text: string;
  value: any;
  isCorrect?: boolean;
  media?: MediaElement[];
}
```

### QuestionResponse

Represents a user's response to a question.

```typescript
interface QuestionResponse {
  questionId: string;
  qType: QuestionType;
  values: any[];
  score: number;
  maxScore: number;
  timeSpent: number;
  isSkipped: boolean;
  isCorrect?: boolean;
  timeStamp: number;
}
```

### PlayerState

Represents the current state of the player.

```typescript
interface PlayerState {
  currentQuestionIndex: number;
  responses: Record<string, QuestionResponse>;
  startTime: number;
  endTime?: number;
  duration: number;
  score: number;
  maxScore: number;
  status: "not_started" | "in_progress" | "completed";
  visitedQuestions: string[];
  skippedQuestions: string[];
}
```

### AssessmentResults

Results data provided when assessment is completed.

```typescript
interface AssessmentResults {
  score: number;
  maxScore: number;
  responses: Record<string, QuestionResponse>;
  duration: number;
  questions: number;
  percentage?: number;
  passed?: boolean;
}
```

## Hooks

### useQumlAPI

Hook for interacting with QUML APIs.

```typescript
function useQumlAPI(config: ApiConfig): {
  fetchHierarchy: (questionSetId: string) => Promise<HierarchyResponse>;
  fetchQuestions: (
    questionIds: string[],
    shuffle?: boolean
  ) => Promise<QuestionsResponse>;
  submitTelemetry: (events: TelemetryEvent[]) => Promise<void>;
};
```

#### Example

```typescript
const { fetchHierarchy, fetchQuestions } = useQumlAPI({
  host: "https://api.example.com",
  endpoint: "/api/question/v1",
});

// Fetch question set hierarchy
const hierarchy = await fetchHierarchy("question-set-123");

// Fetch specific questions
const questions = await fetchQuestions(["q1", "q2", "q3"]);
```

### useTelemetry

Hook for sending telemetry events.

```typescript
function useTelemetry(config: TelemetryConfig): {
  sendTelemetryEvent: (event: Partial<TelemetryEvent>) => Promise<void>;
  sendBatchEvents: (events: Partial<TelemetryEvent>[]) => Promise<void>;
};
```

#### Example

```typescript
const { sendTelemetryEvent } = useTelemetry(telemetryConfig);

// Send a custom event
await sendTelemetryEvent({
  eid: "INTERACT",
  edata: {
    type: "CLICK",
    id: "submit-button",
  },
});
```

## Utility Functions

### cn

Utility function for conditional class names (re-export of clsx).

```typescript
function cn(...inputs: ClassValue[]): string;
```

#### Example

```typescript
import { cn } from "@tekdi/react-quml-player";

const className = cn(
  "base-class",
  {
    active: isActive,
    disabled: isDisabled,
  },
  additionalClass
);
```

## Events and Telemetry

### Telemetry Events

The player automatically sends these telemetry events:

| Event        | Trigger               | Data Included                |
| ------------ | --------------------- | ---------------------------- |
| `START`      | Assessment begins     | Duration, content info       |
| `IMPRESSION` | Question view         | Question ID, timestamp       |
| `INTERACT`   | User interactions     | Interaction type, target     |
| `RESPONSE`   | Answer submission     | Response data, time spent    |
| `ASSESS`     | Answer evaluation     | Score, correctness, duration |
| `END`        | Assessment completion | Summary statistics           |

### Custom Events

You can send custom telemetry events:

```typescript
const { sendTelemetryEvent } = useTelemetry(config.telemetryConfig);

await sendTelemetryEvent({
  eid: "CUSTOM_EVENT",
  edata: {
    type: "custom",
    customField: "customValue",
  },
});
```

## Error Handling

### Error Types

```typescript
interface QumlError extends Error {
  code: string;
  details?: any;
}
```

Common error codes:

- `NETWORK_ERROR`: API request failed
- `INVALID_CONFIG`: Configuration validation failed
- `QUESTION_LOAD_ERROR`: Failed to load questions
- `TELEMETRY_ERROR`: Telemetry submission failed

### Error Boundaries

Wrap the player with error boundaries for graceful error handling:

```typescript
import React from "react";

class QumlErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    console.error("QUML Player Error:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <div>Something went wrong with the assessment player.</div>;
    }

    return this.props.children;
  }
}

// Usage
<QumlErrorBoundary>
  <QumlPlayer {...props} />
</QumlErrorBoundary>;
```

## Performance Considerations

### Bundle Size

The package is optimized for tree-shaking. Import only what you need:

```typescript
// Good - tree-shakeable
import { QumlPlayer } from "@tekdi/react-quml-player";

// Avoid - imports everything
import * as QumlLib from "@tekdi/react-quml-player";
```

### Memory Management

The player automatically cleans up resources, but you can help by:

1. Memoizing configuration objects
2. Using React.memo for wrapper components
3. Cleaning up event listeners in useEffect

### Lazy Loading

For better performance, consider lazy loading:

```typescript
const QumlPlayer = React.lazy(() =>
  import("@tekdi/react-quml-player").then((module) => ({
    default: module.QumlPlayer,
  }))
);
```

## TypeScript Support

The package includes full TypeScript definitions. All interfaces and types are exported for use in your application:

```typescript
import type {
  QumlConfig,
  Question,
  QuestionResponse,
  PlayerState,
  AssessmentResults,
} from "@tekdi/react-quml-player";
```

For advanced TypeScript usage, see the [TypeScript Guide](./TYPESCRIPT.md).
