<?php

declare(strict_types=1);

namespace BadamSoft\WooProductExporter\Exporter\Formats;

use BadamSoft\WooProductExporter\Exporter\Formats\Contracts\WriterInterface;

class FormatManager {
    /**
     * @var array<string, WriterInterface>
     */
    private array $writers = [];

    public function __construct( array $writers = [] ) {
        foreach ( $writers as $writer ) {
            $this->register_writer( $writer );
        }
    }

    public function register_writer( WriterInterface $writer ): void {
        $this->writers[ $writer->getKey() ] = $writer;
    }

    public function get_writer( string $key ): ?WriterInterface {
        if ( ! isset( $this->writers[ $key ] ) ) {
            return null;
        }

        return clone $this->writers[ $key ];
    }

    public function get_default_writer_key(): string {
        $keys = array_keys( $this->writers );

        return $keys[0] ?? 'csv';
    }

    public function get_default_writer(): ?WriterInterface {
        $key = $this->get_default_writer_key();

        return isset( $this->writers[ $key ] ) ? clone $this->writers[ $key ] : null;
    }

    /**
     * @return array<string, string>
     */
    public function get_format_options(): array {
        $options = [];

        foreach ( $this->writers as $writer ) {
            $options[ $writer->getKey() ] = $writer->getLabel();
        }

        return $options;
    }

    public function sanitize_format_key( ?string $key ): string {
        $key = sanitize_key( (string) $key );

        if ( $key && isset( $this->writers[ $key ] ) ) {
            return $key;
        }

        return $this->get_default_writer_key();
    }
}
