import { ServerConfig, Message, Channel } from './types';

export class ServerCache {
    channels: Array<Channel>
    // Channel id's are used to key into the list of messages for that given channel
    messages: Map<Number, Array<Message>>
    config: ServerConfig

    constructor(config: ServerConfig, channels: Array<Channel>, messages: Array<Message>) {
        this.config = config
        this.channels = channels
        for(const message of messages) {
            const ref = this.messages.get(message.cid)

            if(!ref) {
                this.messages.set(message.cid, [message])
            } else {
                ref.push(message)
            }
        }
    }

	url(): String{
		let url = `${this.config.protocol}://${this.config.hostname}`
		// Only add the port WITH THE COLON if the config requires it
		if(this.config.port) {
			url += `:${this.config.port}`
		}

		return url
	}

	push_message(message: Message) {
		let ref = this.messages.get(message.cid)
		if(ref) {
			ref.push(message)
		} else {
			this.messages.set(message.cid, [message])
		}
	}
}

export class Cache {
	// hostname -> Cache
    servers: Map<String, ServerCache>

    constructor(servers: Array<ServerCache>) {
		for(const server of servers) {
			const hostname = server.config.hostname
			this.servers.set(hostname, server)
		}
    }

	add_message(hostname: String, message: Message) {
		let ref = this.servers.get(hostname)
		if(!ref) {
			throw `No server config found for ${hostname}`
		}

		ref.push_message(message)
	}
}

