//  Copyright (c) 2012-2025 Jakub Filipowicz <jakubf@gmail.com>
//
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 2 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc.,
//  51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include <assert.h>

#include "libem400.h"
#include "log.h"
#include "io/chan.h"
#include "io/cchar/cchar.h"
#include "io/iotester.h"
#include "io/mx/mx.h"

typedef chan_t * (*chan_create_f)(int ch_num);

struct chan_kind {
	chan_f_dev_compatible dev_compatible;
	chan_create_f create;
	int max_devices;
};

static const struct chan_kind chan_kinds[] = {
	[EM400_CHANNEL_CHAR] = {
		.dev_compatible = cchar_dev_compatible,
		.create = cchar_create,
		.max_devices = CCHAR_MAX_DEVICES,
	},
	[EM400_CHANNEL_IOTESTER] = {
		.dev_compatible = it_dev_compatible,
		.create = it_create,
		.max_devices = 0,
	},
	[EM400_CHANNEL_MULTIX] = {
		.dev_compatible = mx_dev_compatible,
		.create = mx_create,
		.max_devices = MX_LINE_CNT,
	},
};

// -----------------------------------------------------------------------
int chan_max_devices(unsigned type)
{
	if (type >= EM400_CHANNEL_TYPE_COUNT) {
		return 0;
	}
	return chan_kinds[type].max_devices;
}

// -----------------------------------------------------------------------
bool chan_dev_compatible(unsigned chan_type, unsigned dev_type)
{
	if ((chan_type >= EM400_CHANNEL_TYPE_COUNT) || !chan_kinds[chan_type].dev_compatible) {
		return false;
	}
	return chan_kinds[chan_type].dev_compatible(dev_type);
}

// -----------------------------------------------------------------------
chan_t * chan_create(unsigned num, unsigned type)
{
	if ((type >= EM400_CHANNEL_TYPE_COUNT) || !chan_kinds[type].create) {
		LOGERR("Channel %i: unknown channel type: %d", num, type);
		return NULL;
	}

	chan_t *chan = chan_kinds[type].create(num);
	if (chan) {
		assert(chan->cmd);
		assert(chan->reset);
		assert(chan->shutdown);
		assert(chan->connect_dev);
	}
	// TODO: should chan->num be filled in here?

	return chan;
}

// vim: tabstop=4 shiftwidth=4 autoindent
