def createOptlyData(account_id, project_id, email):
    print "CREATING FOR, ", account_id, project_id, email
    try:
        D = OptlyData.client(GAE_Auth_Cookie, project_id, account_id, {
            "start": False,
            "email": email
        })
        # TODO MAKE THIS 13 DYNAMIC
        D.setExperimentDescriptions(13)
        if D.exp_descriptions == {}:
            return None

        D.setVisitorCount()
        D.createTokenHash()
        D.makeExperimentsCall()  ## sets variation names and original goals
        ## Finish building the hash
        # {exp_id: "goals" { goal_id :  { "name" : goal_name , variation_id: {"conversions": value, type: "type", "sum_of_squares" : SS_val_if_rev_goal, "conversion_rate" " X, "improvment" : X,  "CTB" : X }}}}
        try:
            D.makeResultsCallSlow(10)
        except:
            D.makeResultsCallSlow(5)
        D.makeRevenueCall()
        # D.setGoals()
        D.setResultStatistics()
        return D
    except Exception as e:
        print "Error, ", e
        return None
def createOptlyData(account_id, project_id, email):
    print "CREATING FOR, ", account_id, project_id, email
    try:
        D = OptlyData.client(GAE_Auth_Cookie, project_id, account_id, {
            "start": False,
            "email": email
        })
        # TODO MAKE THIS 13 DYNAMIC
        D.setExperimentDescriptions(13)
        if D.exp_descriptions == {}:
            return None

        D.setVisitorCount()
        D.createTokenHash()
        D.makeExperimentsCall()  ## sets variation names and original goals
        ## Finish building the hash
        # {exp_id: "goals" { goal_id :  { "name" : goal_name , variation_id: {"conversions": value, type: "type", "sum_of_squares" : SS_val_if_rev_goal, "conversion_rate" " X, "improvment" : X,  "CTB" : X }}}}
        try:
            D.makeResultsCallSlow(10)
        except:
            D.makeResultsCallSlow(5)
        D.makeRevenueCall()
        # D.setGoals()
        D.setResultStatistics()
        return D
    except Exception as e:
        print "Error, ", e
        return None
def getProjects(account_id, email):
    D = OptlyData.client(GAE_Auth_Cookie, account_id, account_id, {
        "start": False,
        "email": email
    })
    cookies = D.cookies
    D = createOptlyData(account_id, account_id, email)
    projects = [D] if D else []
    p_jects = requests.get(
        "https://www.optimizely.com/api/projects.json",
        cookies=cookies).json()['projects']
    for p in p_jects:
        if p['project_status'] == "Archived" or str(p['id']) == account_id:
            continue
        else:
            print "CREATING DATA OBJ FOR: a_id, p_id", account_id, p['id']
            try:
                D = createOptlyData(account_id, p['id'], email)
            except Exception as e:
                ERRORS.append((account_id, project_id, email))
                D == None
            if D:
                projects.append(D)
                for e in D.errors:
                    ERRORS.append(e)
    return projects
def getProjects(account_id, email):
    D = OptlyData.client(GAE_Auth_Cookie, account_id, account_id, {
        "start": False,
        "email": email
    })
    cookies = D.cookies
    D = createOptlyData(account_id, account_id, email)
    projects = [D] if D else []
    p_jects = requests.get("https://www.optimizely.com/api/projects.json",
                           cookies=cookies).json()['projects']
    for p in p_jects:
        if p['project_status'] == "Archived" or str(p['id']) == account_id:
            continue
        else:
            print "CREATING DATA OBJ FOR: a_id, p_id", account_id, p['id']
            try:
                D = createOptlyData(account_id, p['id'], email)
            except Exception as e:
                ERRORS.append((account_id, project_id, email))
                D == None
            if D:
                projects.append(D)
                for e in D.errors:
                    ERRORS.append(e)
    return projects
def make_segment(segment_id, segment_value, m_ago):
	s = OptlyData.client(GAE_Auth_Cookie, project_id, account_id, { "optimizely_session": D.optimizely_session,
													 				"segment_id" : segment_id,
																	"segment_value": segment_value,
																	"segment_value_maps": segment_value_maps,
																	"token_hash" : D.token_hash,
																	"start" : False,
																	"exp_descriptions": D.exp_descriptions.copy(),
																	"account_token": D.account_token,
																	"D": D
																	})
	s.setExperimentDescriptions(m_ago)
	s.setVisitorCount()
	# Removes Experiments where this segment id, value pair does not make up x% of traffic
	removeLowExpVisitors(s, .05)
	if len(s.exp_descriptions) == 0:
		return None
	s.makeExperimentsCall() ## sets variation names and original goals	
	## Finish building the hash 
	# {exp_id: "goals" { goal_id :  { "name" : goal_name , variation_id: {"conversions": value, type: "type", "sum_of_squares" : SS_val_if_rev_goal, "conversion_rate" " X, "improvment" : X,  "CTB" : X }}}} 
	s.makeRevenueCall()
	# D.setGoals()
	s.setResultStatistics()
	s.setGoalNames()
	return s
def make_segment(segment_id, segment_value, m_ago):
    s = OptlyData.client(
        GAE_Auth_Cookie, project_id, account_id, {
            "optimizely_session": D.optimizely_session,
            "segment_id": segment_id,
            "segment_value": segment_value,
            "segment_value_maps": segment_value_maps,
            "token_hash": D.token_hash,
            "start": False,
            "exp_descriptions": D.exp_descriptions.copy(),
            "account_token": D.account_token,
            "D": D
        })
    s.setExperimentDescriptions(m_ago)
    s.setVisitorCount()
    # Removes Experiments where this segment id, value pair does not make up x% of traffic
    removeLowExpVisitors(s, .05)
    if len(s.exp_descriptions) == 0:
        return None
    s.makeExperimentsCall()  ## sets variation names and original goals
    ## Finish building the hash
    # {exp_id: "goals" { goal_id :  { "name" : goal_name , variation_id: {"conversions": value, type: "type", "sum_of_squares" : SS_val_if_rev_goal, "conversion_rate" " X, "improvment" : X,  "CTB" : X }}}}
    s.makeRevenueCall()
    # D.setGoals()
    s.setResultStatistics()
    s.setGoalNames()
    return s
account_id = 183850804
project_id = 183850804
name = a_name+"_%s.xlsx" % str(datetime.date.today())


conversion_limit = 50 ## Minimum number of conversions needed in variation and original to be considered 

print "************************** Running %s Dashboard **************************" % a_name

if debugging:
	try:
		D = pickle.load(open( "pickles/results%s" % (str(account_id) + "," + str(project_id)),  "rb" ))
	except Exception as e:
		print e
		D = OptlyData.client(GAE_Auth_Cookie, project_id, account_id, {"start": True, "email": email, "months_ago" : 12})
		pickle.dump(D, open( "pickles/results%s" % (str(account_id) + "," + str(project_id)), "wb" ))
else: 
	D = OptlyData.client(GAE_Auth_Cookie, project_id, account_id, {"start": True, "email": email, "months_ago" : 12})

num_experiments = len(D.exp_descriptions.keys())
segment_names = {}
segment_value_maps = {} # exp: seg value map
segment_id_value_pairs = {}

def getSegmentNames():
	s_names = {}
	for segment in requests.get("https://www.optimizely.com/api/projects/%s/segments.json?default_segments=true&token=%s" % (str(project_id), D.account_token), cookies=D.cookies).json()["segments"]:
		s_names[str(segment['id'])] = segment["name"]
	return s_names
conversion_limit = 50  ## Minimum number of conversions needed in variation and original to be considered

print "************************** Running %s Dashboard **************************" % a_name

if debugging:
    try:
        D = pickle.load(
            open(
                "pickles/results%s" %
                (str(account_id) + "," + str(project_id)), "rb"))
    except Exception as e:
        print e
        D = OptlyData.client(GAE_Auth_Cookie, project_id, account_id, {
            "start": True,
            "email": email,
            "months_ago": 12
        })
        pickle.dump(
            D,
            open(
                "pickles/results%s" %
                (str(account_id) + "," + str(project_id)), "wb"))
else:
    D = OptlyData.client(GAE_Auth_Cookie, project_id, account_id, {
        "start": True,
        "email": email,
        "months_ago": 12
    })

num_experiments = len(D.exp_descriptions.keys())