import csv
import random
import string
import numpy as np

def create_index(weight,movie_file,index_file):
	f=open(movie_file,'rb')
	csvf = csv.DictReader(f, delimiter=',',quotechar='"')
	index = {}
	for line in csvf:
		people = []
		m = float(line['score'])

		dir_str = line['directors'][1:-1]
		dirs = dir_str.split(", ")
		for person in dirs:
			people.append([person.strip()[1:-1],weight[0]])

		wr_str = line['writers'][1:-1]
		wrs = set(wr_str.split(", "))
		for person in wrs:
			people.append([person.strip()[1:-1],weight[1]])

		act_str = line['actors'][1:-1]
		act = act_str.split(", ")
		for i in range(len(act)):
			if (i<2):
				people.append([act[i].strip()[1:-1],weight[2]])
			elif i<4:
				people.append([act[i].strip()[1:-1],weight[3]])
			else:
				people.append([act[i].strip()[1:-1],weight[4]])

		for person in people:
			key = person[0]
			if ('more credit' in key):
				continue
			if ('unknown' in key):
				continue
			if (not index.has_key(key)):
				index.update({key:[m,person[1]]})
			else:
				om = index[key][0]
				ow = index[key][1]
				nm = (om*ow+person[1]*m)/(ow+person[1])
				nw = ow+person[1]
				index[key]=[nm,nw]
	f.close()
	return index

def create_movie(test_file,ppl):
	f=open(test_file,'rb')
	csvf = csv.DictReader(f, delimiter=',',quotechar='"')
	movie={}
	for line in csvf:
		dir_str = line['directors'][1:-1]
		dirs=[]
		for s in dir_str.split(", "):
			if not ('more credit' in s[1:-1]):
				if ppl.has_key(s[1:-1]):
					dirs.append( string.atof( ppl[s[1:-1]][0]) )#if the person in known, give its value from ppl
				else:
					dirs.append(random.gauss(5.9,0.764323))# if the person is unknown, give it a random value generated by normal distribution
		wr_str = line['writers'][1:-1]
		wrs=[]
		for s in wr_str.split(", "):
			if not ('more credit' in s[1:-1]):
				if ppl.has_key(s[1:-1]):
					wrs.append( string.atof(ppl[s[1:-1]][0]) )
				else:
					wrs.append(random.gauss(5.9,0.764323))

		act_str = line['actors'][1:-1]
		acts=[]
		for s in act_str.split(", "):
			if not ('more credit' in s[1:-1]):
				if ppl.has_key(s[1:-1]):
						acts.append(string.atof(ppl[s[1:-1]][0]))
				else:
						acts.append(random.gauss(5.9,0.764323))
		dir=np.mean(np.array(dirs))
		wr=np.mean(np.array(wrs))
		al=0
		asup=0
		nl=0
		ns=0
		ao=0
		nao=0
		for i in range(len(acts)):
			if acts[i]!=0:
				if (i<2):
					al+=acts[i]
					nl+=1
				elif i<4:
					asup+=acts[i]
					ns+=1
				else:
					ao+=acts[i]
					nao+=1
		if nl!=0:
			al=al/nl
		if ns!=0:
			asup=asup/ns
		if nao!=0:
			ao=ao/nao
		movie.update( {line['imdb_id']:[dir,wr,al,asup,ao,string.atof(line['score'])]} )
	return movie

def write_index(index,index_file="IndexedArtists.csv"):
	f = open(index_file,'w')
	f.write('Name,Score,Weight\n')
	for key in index.keys():
		f.write(key+','+str(index[key][0])+','+str(index[key][1])+'\n')
	f.close()