#!/usr/bin/python
# coding: utf-8
import getpass
import os
import lxml
from crontab import CronTab
from bs4 import BeautifulSoup as bsoup
import urllib2,cookielib
from urllib2 import urlopen
import requests as rq
from xml.dom.minidom import parse, parseString
import sys
from math import ceil
from sys import argv
import pynotify
import subprocess
import pickle
import time
import requests
import subprocess
from os import popen
from random import choice
tab = CronTab(user=getpass.getuser())

def sendmessage(title, subtitle, info_text,):
    pynotify.init("Test")
    notice = pynotify.Notification(title, subtitle, info_text,)
    notice.show()
    subprocess.Popen("//usr//bin//mplayer //usr//share//sounds//freedesktop//stereo//bell.oga" + "> /dev/null 2>&1 || true", shell = True)
    return

def StopCricLive(stop):
    #If any network issue while fecthing from crontab
    tab.remove_all(comment="CricLiveNotifier")
    tab.write()
    try:
        os.remove('CricLiveNotifier.txt')
    except OSError:
        pass
    if stop: sys.exit(0)
def ConnectionIssue():
    #If any network issue while fecthing livematches.xml
    print "Something went wrong.Please check your internet connection."
    sys.exit(0)
if len(argv) == 1:
    os.system('clear')
    print "Please wait.."
    try:
    	site = "http://synd.cricbuzz.com/j2me/1.0/livematches.xml"
        livematches,livematches1 = rq.get(site),rq.get(site)
    except Exception:
        ConnectionIssue()
    if "<html" in livematches:
        ConnectionIssue()
    soup = bsoup(livematches1.content, "xml")
    match_list = {}
    os.system('clear')
    sp_status = ""
    #Pulling livematches data from cricbuzz xml using BeautifulSoup for first notification after setup
    for idx,mtch in enumerate(soup.findAll('match')):
        for sts in mtch.findAll('state'):
            if sts.get('mchState') == 'tea' or sts.get('mchState') == 'lunch' or sts.get('mchState') == 'innings break' or sts.get('mchState') == 'inprogress':
                if sts.get('mchState') == 'tea': sp_status = "Tea Break"
                if sts.get('mchState') == 'lunch': sp_status = "Lunch Break"
                if sts.get('mchState') == 'innings break': sp_status = "Innings Break"
                match_list[idx+1] = mtch.get('datapath')
                print '{0}: {1} - {2}'.format(idx+1,mtch.get('mchDesc'),mtch.get('mnum'))
    #Checking is there any match available now for score update
    if any(match_list):
        match_no = raw_input("Select your Match by Entering the Number > ")
        sound_alert = raw_input("Notification with sound (Y/N) > ")
        sound_alert = (sound_alert.lower() == 'y')
        auto_close = raw_input("Auto Close Notification after seconds( 0 - 15 && manual close - 0) > ")
        match_link_com = match_list[int(match_no)] + "commentary.xml"
        os.system('clear')
        print "Please wait.."
        try:
            site1 = match_link_com
            commentary,commentary1 = rq.get(site1),rq.get(site1)
        except Exception:
            ConnectionIssue()
        if "<html" in commentary:
            ConnectionIssue()