from django.core.management.base import BaseCommand, CommandError, NoArgsCommand
from futstats.models import *
import urllib, urllib2, time, unicodedata
import os, random, socket
import datetime as dt
from bs4 import BeautifulSoup
from django.conf import settings
from futstats.views import *

class Command(NoArgsCommand):
    def handle_noargs(self, **options):
        t0 = time.time()
        urls = ['http://resultados.as.com/resultados/futbol/primera/20'+str(i).zfill(2)+'_20'+str(i+1).zfill(2)+'/calendario' for i in range(1,15)]
        for url in urls:
            t1 = time.time()
            temporada = int(url[url.index("_")-2:url.index("_")])
            if not Partido.objects.filter(liga=1, temporada=temporada,jugado=True).count() == 380:
                print "processing temporada:",temporada
                soup = BeautifulSoup(urllib2.urlopen(url).read())
                t =  soup.findAll('div', {'class' : 'fecha-jor-cal'})
                months = {'Ene':1,'Feb':2,'Mar':3,'Abr':4,'May':5,'Jun':6,'Ago':8,'Sep':9,'Oct':10,'Nov':11,'Dic':12}
                for jornada in t:  
                    date = jornada.find('span', {'class' :'dias-cal s-right'}).text.split("- ") 
                    if len(date) == 1: d = date[0]
                    else: d = date[1] 
                    dia, mes = d.split(" ")
                    m_num = months[mes]
                    if m_num < 7: y = 2000+temporada+1
                    else: y = 2000+temporada
                    d = dt.datetime(y,m_num,int(dia))
                    j_id = int(jornada.find('span', {'class' : 'jor-cal s-left'}).text.split("Jornada ")[1])
                    print "jornada",j_id
                    teams = jornada.findAll('span', {'itemprop' : 'name'}, text=True)
                    if not teams:
                        lteams = jornada.findAll('td', {'class' : 'txt-al-r'})
                        vteams = jornada.findAll('td', {'class' : 'txt-al-l'})
                        for f, b in zip(lteams, vteams):
                            local = unicodedata.normalize('NFKD',f.find('a').text).encode('ascii','ignore')
                            visitante = unicodedata.normalize('NFKD',b.find('a').text).encode('ascii','ignore')
                            createTeam(local)
                            createTeam(visitante)
                            #Create match
                            saveMatch(j_id, local, visitante, d, temporada, 1) 
                    else:
                        for local, visitante in zip(teams[0::2], teams[1::2]):
                            local = unicodedata.normalize('NFKD',local.text).encode('ascii','ignore')
                            visitante = unicodedata.normalize('NFKD',visitante.text).encode('ascii','ignore')
                            #Create local and visitor match
                            createTeam(local)
                            createTeam(visitante)
                            #Create match
                            saveMatch(j_id, local, visitante, d, temporada, 1)
                t =  soup.findAll('a', {'class' : 'resultado resul_post'})
                #Record played matches into DB
                for link in t:
                    print "processing link:",link
                    try:
                        soup = BeautifulSoup(urllib2.urlopen(link['href'],timeout = 10))
                        process(soup, temporada, 1)
                    except socket.timeout:
                        pass
                if temporada == 14:
                    print "ENTRO BUILDSTATS"
                    buildStats(14, 1)
                    print "predict..."
                    predict()
            print time.time() - t1, "seconds process ",temporada
        print time.time() - t0, "TOTAL TIME" 
