from tempfile import mkstemp
import os.path
from pprint import pprint

from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.core.context_processors import csrf

from qmpy import INSTALL_PATH
from qmpy import *

ndict = {1:'elements',
         2:'binary phases',
         3:'ternary phases',
         4:'quaternary phases',
         5:'pentenary phases',
         6:'hexanary phases'}

def construct_flot(phase_dict):
    data = []
    for p, v in phase_dict.items():
        series = {'label':p.name, 'data':v}
        data.append(series)
    return json.dumps(data)

def composition_view(request, search=None):
    data = {'search':''}
    composition = ''
    space = []
    if request.method == 'POST':
        p = request.POST
        search = p.get('search', '')
        data.update(p)
    if not search:
        return render_to_response('materials/composition.html',
                data,
                RequestContext(request))

    if search.count('-') == 0:
        composition = search
    else:
        space = search

    if composition:
        comp = Composition.get(composition)
        ps = PhaseSpace('-'.join(comp.comp.keys()))
        data['pd'] = ps.phase_diagram.get_flot_script("phasediagram")
        data['search'] = composition
        data['composition'] = comp
        data['plot'] = comp.relative_stability_plot.get_flot_script()
        data['results'] = comp.sorted_distinct
        energy, gs = ps.gclp(comp.name)
        data['gs'] = Phase.from_phases(gs)
        data['compound'] = comp.ground_state
        data['singlephase'] = ( len(gs) == 1 )
        data['space'] = '-'.join(comp.comp.keys())
        return render_to_response('materials/composition.html', 
                data,
                RequestContext(request))
    elif space:
        ps = PhaseSpace(space)
        data['search'] = space
        data['pd'] = ps.phase_diagram.get_flot_script("phasediagram")
        data['stable'] = [ p.calculation.entry for p in ps.stable ]
        comps = Composition.get_list(space)
        results = []
        for c in comps:
            results += c.sorted_distinct
        data['results'] = results
        return render_to_response('materials/phasespace.html', 
                data,
                RequestContext(request))

def generic_composition_view(request, search=None):
    data = {'search':search}
    composition = ''
    space = []
    if request.method == 'POST':
        p = request.POST
        search = p.get('search', '')
        data.update(p)
    if not search:
        return render_to_response('materials/generic_composition.html',
                data,
                RequestContext(request))
        
    gc = GenericComposition(search)
    data['gc'] = gc
    return render_to_response('materials/generic_composition.html', 
            data,
            RequestContext(request))
