/* Copyright 2018 Romain "Artefact2" Dal Maso <artefact2@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "gumble.h"

static const int piece_values[] = {
	0, 0,
	1000, -1000,
	3010, -3010,
	3000, -3000,
	5000, -5000,
	9000, -9000,
};

static const unsigned char square_weights[] = {
	1, 1, 1, 1, 1, 1, 1, 1,
	1, 2, 2, 2, 2, 2, 2, 1,
	1, 2, 3, 3, 3, 3, 2, 1,
	1, 2, 3, 4, 4, 3, 2, 1,
	1, 2, 3, 4, 4, 3, 2, 1,
	1, 2, 3, 3, 3, 3, 2, 1,
	1, 2, 2, 2, 2, 2, 2, 1,
	1, 1, 1, 1, 1, 1, 1, 1,
};

/* XXX */
int cch_evaluate_position(const cch_board_t* b, cch_movelist_t ml, unsigned char stop) {
	int eval = 0;

	if(stop == 0) {
		if(CCH_IS_OWN_KING_CHECKED(b)) { /* XXX */
			/* Checkmate! We lost. */
			return -CCH_CHECKMATE_SCORE - 500 + b->turn + b->smoves;
		} else {
			/* Stalemate! */
			return 0;
		}
	}

	/* Count material */
	for(unsigned char i = 2; i < 12; ++i) {
		/* XXX: is this faster than just iterating over the board ? */
		eval += piece_values[i] * __builtin_popcountll(b->pieces[i]);
	}

	if(!b->side) eval = -eval;

	/* Mobility & threats */
	for(unsigned char i = 0; i < stop; ++i) {
		if(CCH_GET_SQUARE(b, ml[i].end)) {
			eval += 10;
		} else {
			eval += square_weights[ml[i].end];
		}
	}

	return eval;
}
