<?php

class Rds_Bt50_Scorecard_Dictionary_Generator {
	public static $bt50DistrictRegex = '/(?P<stateCode>[a-z]{0,2})(?P<district>[0-9]+)/i';

	public function __construct() {
	}

	public static function generateBt50PresenceDictionary($presenceResponse) {
		if (!$presenceResponse) { return array(); }

		$dictionary = array_reduce($presenceResponse['LegislatorVotePresense'], function($memo, $legislator) {
			$key = $legislator['LegislatorID'];
			$memo[$key] = $legislator;
			return $memo;
		}, array());
		return $dictionary;
	}

	public static function generateBt50ScorecardDictionary($scorecardResponse) {
		$dictionary = array_reduce($scorecardResponse['Legislators'], function($memo, $legislator) {
			$key = $legislator['LegislatorID'];
			$memo[$key] = $legislator;
			return $memo;
		}, array());
		return $dictionary;
	}

	public static function createBt50LegislatorDictionary ($legislators) {
		$dictionary = array_reduce($legislators, function($memo, $legislator) {
			$key = self::bt50LegislatorKey($legislator);
			$memo[$key] = $legislator;
			return $memo;
		}, array());
		return $dictionary;
	}

	public static function generateOsLegislatorDictionary ($legislators) {
		$dictionary = array_reduce($legislators, function($memo, $legislator) {
			$key = self::osLegislatorKey($legislator);
			$memo[$key] = $legislator;
			return $memo;
		}, array());
		return $dictionary;
	}

	public static function bt50LegislatorKey($bt50Legislator) {
		// eg. NM7JW
		preg_match(self::$bt50DistrictRegex, $bt50Legislator['District'], $matches);
		$bt50Key = strtoupper($matches['stateCode']);
		$bt50Key .= strtoupper($bt50Legislator['Chamber'][0]);
		$bt50Key .= (int) $matches['district'];
		$bt50Key .= $bt50Legislator['FirstName'][0];
		$lastNames = explode(' ', $bt50Legislator['LastName']);
		$bt50Key .= end($lastNames)[0]; // first letter of final name in last names
		return $bt50Key;
	}

	public static function osLegislatorKey($osLegislator) {
		$osKey = strtoupper($osLegislator['state']);
		$chamber = self::normalizeOsChamber($osLegislator['chamber']);
		$osKey .= strtoupper($chamber[0]);
		$osKey .= $osLegislator['district'];
		$osKey .= $osLegislator['first_name'][0];
		$lastNames = explode(' ', $osLegislator['last_name']);
		$osKey .= end($lastNames)[0]; // first letter of final name in last names
		$fallbackMappings = [
			'NM7PW' => 'NM7JW' // NM  John Woods in BT50 is Pat Woods on OS
		];
		if (array_key_exists($osKey, $fallbackMappings)) {
			return $fallbackMappings[$osKey];
		}
		return $osKey;
	}

	public static function normalizeOsChamber($chamber) {
		if (strtolower($chamber) == 'lower') {
			return 'House';
		}
		return 'Senate';
	}
}
