import $ from 'jquery';
import {fetchObj, loadObj} from './objutils';

/**
 * Initialize the parameters
 * @param {any} context the program context
 */
export function initParams(context: any) {
	context.params = {
		distance: parseFloat(<string>$('#distance').val()) +
			parseFloat(<string>$('#distancefine').val()),
		circleSize: parseFloat(<string>$('#circlesize').val()),
		fov: parseFloat(<string>$('#fov').val()),
		len: 0,
		range: 0,
		rot: {
			x: parseFloat(<string>$('#rotx').val()),
			y: parseFloat(<string>$('#roty').val()),
			z: parseFloat(<string>$('#rotz').val()),
		},
		rotSpeed: parseFloat(<string>$('#rotspeed').val()),
		instanceNumber: parseFloat(<string>$('#instance').val()),
		squareRotation: 0,
		camRot: {
			x: 0,
			y: 0,
		},
		camPos: {
			x: 0,
			y: 0,
			z: 0,
		},
		keyboard: {
			w: false,
			a: false,
			s: false,
			d: false,
			space: false,
			shift: false,
		},
	};
}

/**
 * Initialize the cache with an object
 * @param {any} context the program context
 */
export async function initCache(context: any) {
	const racerData = await fetchObj('/static/objs/racer.obj');
	const racerObj = loadObj(racerData);
	context.cache = {
		fox: null,
		mecha: null,
		racer: racerObj,
		sphere: null,
		teapot: null,
	};
	context.params.len = racerObj.indices.length;
	context.params.range = racerObj.range;
}

/**
 * Set the program info
 * @param {any} context the program context
 */
export function setProgramInfo(context: any) {
	context.programInfo = {
		program: context.shaderProgram,
		attribLocations: {
			vertexPosition: context.gl.getAttribLocation(context.shaderProgram,
				'aVertexPosition'),
			vertexNormal: context.gl.getAttribLocation(context.shaderProgram,
				'aVertexNormal'),
			textureCoord: context.gl.getAttribLocation(context.shaderProgram,
				'aTextureCoord'),
		},
		uniformLocations: {
			projectionMatrix: context.gl.getUniformLocation(
				context.shaderProgram, 'uProjectionMatrix'),
			viewMatrix: context.gl.getUniformLocation(
				context.shaderProgram, 'uviewMatrix'),
			modelMatrix: context.gl.getUniformLocation(
				context.shaderProgram, 'umodelMatrix'),
			normalModelMatrix: context.gl.getUniformLocation(
				context.shaderProgram, 'unormalModelMatrix'),
			uSampler: context.gl.getUniformLocation(
				context.shaderProgram, 'uSampler'),
			time: context.gl.getUniformLocation(
				context.shaderProgram, 'time'),
		},
	};
}
