#include <string.h>

#include "hsi.h"
#include "hud.h"
#include "instruments.h"
#include "magnetic_compass.h"
#include "../util/memory.h"
#include "pm.h"
#include "prompt.h"
#include "render.h"
#include "terminal.h"

#define viewer_IMPORT
#include "viewer.h"


viewer * viewer_new(craft * c)
{
	viewer *v;

	v = (viewer *) memory_allocate(sizeof(viewer), NULL);
	memset(v, 0, sizeof(viewer));

	v->vl_next = vl_head;
	vl_head = v;

	v->next = c->vl;
	c->vl = v;

	v->viewer_state = ViewerStateNormal;
	v->c = c;
	v->watchedCraft = NULL;
	v->hasFocus = FALSE;
	v->hasComm = TRUE;

	/* FIXME: to-do fields
	v->w = ...;
	v->v = ...;
	v->dpy = ...;
	v->win = ...;
	v->gc = ...;
	v->cn = ...;
	v->protocolsAtom = ...;
	v->deleteWindowAtom = ...;
	v->closedownAtom = ...;

	v->hud_yCenter = ...
	*/

	/*
		All the Rect, drawnItem and scale_Type fields are in charge
		of the layout manager (see "windows" module).
	*/

	v->zoom = 100; // 100%
	v->hud_mode = FALSE;

	/* FIXME: to-do
	v->xscaleFactor = ...
	v->yscaleFactor = ...
	v->z =
	v->rz = ...
	v->radarImage = ...
	v->radarImageCount = ...
	*/
	v->browseBase = 0;
	v->browseSelectedItem = -1;
	v->browseClickTime = 0;

	/* Set v->viewDirection and v->viewUp: */
	render_setOutsideView(c, v, render_VIEW_FORWARD);

	v->hud = NULL;
	v->magnetic_compass = NULL;
	v->hsi = NULL;
	v->adf = NULL;
	v->sounds = NULL;
	v->inst = NULL;
	v->terminal = NULL;
	v->prompt = NULL;

	return v;
}


void viewer_free(viewer *v)
{
	viewer *update_cur;
	craft  *c;

	/*
		Release attached services:
	*/

	memory_dispose(v->sounds);
	hud_free(v);
	magnetic_compass_free(v);
	memory_dispose(v->adf);
	hsi_free(v);
	instruments_free(v);
	terminal_free(v);
	prompt_free(v);

	/*
		Close the window
	*/

	memory_dispose(v->v);
	memory_dispose(v->w);
	memory_dispose(v->gui);

	/*
		Remove this viewer from the craft's list of viewers:
	*/

	c = v->c;
	
	if( c->vl == v ){
		c->vl = v->next;
	} else {
		update_cur = c->vl;
		while( update_cur->next != v )
			update_cur = update_cur->next;
		update_cur->next = v->next;
	}

	/*
		Remove viewer from the list of viewers:
	*/

	if( vl_head == v ){
		vl_head = v->vl_next;
	} else {
		update_cur = vl_head;
		while( update_cur->vl_next != v )
			update_cur = update_cur->vl_next;
		update_cur->vl_next = v->vl_next;
	}

	memory_dispose(v);

}
