#!/usr/bin/env python

from os import system
import commands
#import sys
from random import choice
import curses
import time

def conswidth():
    rows,columns = commands.getoutput("stty size").split()
    global col; global row;
    col = int(columns)
    row = int(rows)

def maxL(stringline):
    if ("\n" in stringline)==False:
	return len(stringline)
    else:
    	std = stringline.split("\n")
    	max = 0
    	for line in std:
	    if(len(line)>max):
	        max = len(line)
        return max

def sentsplit(stringline, line, startc, timer, charcs=True):  #charcs false doesnt work for \n lines
    opos = startc
    if(charcs == True):               
	listn = list(stringline)

    else:listn = stringline.split()
    for word in listn:
        if(word == "\n"):
            line += 1
            opos = startc
            continue
            
        screen.addstr(line, opos, word)
        screen.refresh()
        time.sleep(timer)
        if(charcs==False):opos += len(word)
	opos += 1	

def get_param(prompt_string):
     screen.clear()
     screen.border(0)
     screen.addstr(2, 2, prompt_string)
     screen.refresh()
     input = screen.getstr(4, 3, 50)
     return input

def maxL(stringline):
    if ("\n" in stringline)==False:
        return len(stringline)
    else:
        std = stringline.split("\n")
        max = 0
        for line in std:
            if(len(line)>max):
                max = len(line)
        return max

def fitter(strlist): 
    conswidth()
    if isinstance(strlist, basestring):
        start = int((col-maxL(strlist))/2)
        return start
    else:
        maxc = 0
        maxlist = []
        for lis in strlist:
            maxc = maxL(lis)
            if(maxc<col):
                stt = [lis,int((col-maxL(lis))/2)]
                maxlist.append(stt)     #string and starting position
        
        return maxlist   #returns stringlist and starting position 

def execute_cmd(cmd_string, warn=False):
    system("clear")
    a = system(cmd_string)
    print ""
    if a == 0:
        print "Command executed correctly"
    elif(warn):
        raw_input("Press Ctrl+C")
    else:
        print ""


def musicLib(line, startc, timer, direct="/home/user/MyDocs/.sounds/"):
    conswidth() #updates row
    stringline = commands.getoutput("ls "+direct)
    opos = startc
    stline = line
    listn = stringline.splitlines(); filelist = [];
    ii = ord('a')
    try: 
        tot = 0
        for ink in listn:
            tot += len(ink)
        largst = int(tot/len(listn))+startc
    except ValueError:
        return []

    boo = 0
    for word in listn:  #the current line (still has words in it)
        if(line >= row-2):
             line = stline
             if(largst < col): boo += 1

        if(boo>0): opos = largst*boo
        else: opos = startc
        line += 1
        if( '.' in word):
            filelist.append(word);screen.addstr(line, opos, chr(ii)+" - ");ii += 1;
        else:
            screen.addstr(line, opos, "    ")

        opos += 5
        if(len(word)>(col-1)):
            www = word.split(num=2);
            screen.addstr(line, opos, www[0])
            screen.refresh()
            time.sleep(timer)
            screen.addstr(line, opos, www[1])

        else:
            screen.addstr(line, opos, word)
            screen.refresh()
            time.sleep(timer)
    #    opos += len(word)+1
    return filelist



def ascii(type):
    if type=="logo":
        logo1 = "           _                      __ _\n     _ __ | |__   ___  _ __   ___/ _\ |_ _ __ ___  __ _ _ __ ___\n    | '_ \| '_ \ / _ \| '_ \ / _ \ \| __| '__/ _ \/ _` | '_ ` _ \ \n    | |_) | | | | (_) | | | |  __/\ \ |_| | |  __/ (_| | | | | | |\n    | .__/|_| |_|\___/|_| |_|\___\__/\__|_|  \___|\__,_|_| |_| |_|\n    |_|"; 
        logo2 = "         _               _____ _\n     ___| |_ ___ ___ ___|   __| |_ ___ ___ ___ _____\n    | . |   | . |   | -_|__   |  _|  _| -_| .'|     |\n    |  _|_|_|___|_|_|___|_____|_| |_| |___|__,|_|_|_|\n    |_|"; 
        slogo1 = "      _                 ___ _\n _ __| |_  ___ _ _  ___/ __| |_ _ _ ___ __ _ _ __\n| '_ \ ' \/ _ \ ' \/ -_)__ \  _| '_/ -_) _` | '  \ \n| .__/_||_\___/_||_\___|___/\__|_| \___\__,_|_|_|_|\n|_|     "
        slogo2 = "         __                 ______\n   ___  / /  ___  ___  ___ / __/ /________ ___ ___ _\n  / _ \/ _ \/ _ \/ _ \/ -_)\ \/ __/ __/ -_) _ `/  ' \ \n / .__/_//_/\___/_//_/\__/___/\__/_/  \__/\_,_/_/_/_/\n/_/         "
        slogo3 = "     _ |_  _  _  _ (~_|_ _ _  _  _ _\n    |_)| |(_)| |(/__) | | (/_(_|| | |\n    |     "
        slogo4 = "   .            .-. .\n.-.|-. .-..-..-,`-.-|-.-..-,.-. .-.-.\n|-'' '-`-'' '`'-`-' '-'  `'-`-`-' ' '\n'    "
        cyberS = " ___  _  _ ____ __ _ ____ ____ ___ ____ ____ ____ _  _\n |--' |--| [__] | \| |=== ====  |  |--< |=== |--| |\/|"
        cyber= "  _____  _     _  _____  __   _ _______ _______ _______  ______ _______ _______ _______\n |_____] |_____| |     | | \  | |______ |______    |    |_____/ |______ |_____| |  |  |\n |       |     | |_____| |  \_| |______ ______|    |    |    \_ |______ |     | |  |  |"
        bigc = "________________________________________________________________________\n                                      __\n            /                       /    )\n------__---/__----__----__----__----\------_/_---)__----__----__---_--_-\n    /   ) /   ) /   ) /   ) /___)    \     /    /   ) /___) /   ) / /  )\n___/___/_/___/_(___/_/___/_(___ _(____/___(_ __/_____(___ _(___(_/_/__/_\n  /\n /"
        avat = " ____  _     ____  _      _____ ____ _____ ____  _____ ____  _\n/  __\/ \ /|/  _ \/ \  /|/  __// ___X__ __X  __\/  __//  _ \/ \__/|\n|  \/|| |_||| / \|| |\ |||  \  |    \ / \ |  \/||  \  | / \|| |\/||\n|  __/| | ||| \_/|| | \|||  /_ \___ | | | |    /|  /_ | |-||| |  ||\n\_/   \_/ \|\____/\_/  \| \____\\____/ \_/ \_/\_\ \___\ \/ \|\_/  \|"
        digS = "+-+-+-+-+-+-+-+-+-+-+-+\n|p|h|o|n|e|S|t|r|e|a|m|\n+-+-+-+-+-+-+-+-+-+-+-+"
        keybS = " ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____\n||p |||h |||o |||n |||e |||S |||t |||r |||e |||a |||m ||\n||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__||\n|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|"
        return [logo1, logo2, slogo1, slogo2, slogo3, slogo4, cyberS, cyber, bigc, avat, digS, keybS]
        
    
    elif type=="coming soon":
        textt=" ____ ____ ____ ____ ____ ____ ________ ____ ____ ____ ____ \n||C |||o |||m |||i |||n |||g |||      |||S |||o |||o |||n ||\n||__|||__|||__|||__|||__|||__|||______|||__|||__|||__|||__||\n|/__\|/__\|/__\|/__\|/__\|/__\|/______\|/__\|/__\|/__\|/__\|"
        textSs= "                _________                _____\n__  ____/____________ ______(_)_____________ _\n_  /    _  __ \_  __ `__ \_  /__  __ \_  __ `/\n/ /___  / /_/ /  / / / / /  / _  / / /  /_/ /\n\____/  \____//_/ /_/ /_//_/  /_/ /_/_\__, /\n   _____  ______                     /____/\n       /__  ___/__________________\n      \ _____ \_  __ \  __ \_  __ \ \n     __ ____/ // /_/ / /_/ /  / / /\n      _ _____/ \____/\____//_/ /_/"
        textS= "________               _____               ________\n_  ____/___________ ______(_)_____________/  _ ___/__________________\n  /   _  __ \_  __ `__ \_  /__ __ \_  __ `/_____ \_  __ \  __ \_  __ \ \n /___ / /_/ /  / / / / /  /_  / / /  /_/ / ____/ // /_/ / /_/ /  / / /\n____/ \____//_/ /_/ /_//_/ /_/ /_/_\__, / / ____/ \____/\____//_/ /_/\n                                  /____/"
        textGs=" /~~            '           /~~\ \n|   /~\|/~\ /~\ ||/~\ /~~|  `--./~\/~\|/~\ \n \__\_/|   |   |||   |\__|  \__/\_/\_/|   |\n                      \__| "
        textIs="   __                          ___\n ,'_/ _   _     ()_     _    ,' _/ _   _   _\n/ /_,'o| / \'\ /7/ \/7,'o|  _\ `.,'o|,'o| / \/7\n|__/|_,'/_nn_////_n_/ |_,' /___,'|_,'|_,'/_n_/\n                      _// "
        textD=" _____                 _               _____\n/  __ \               (_)             /  ___|\n| /  \/ ___  _ __ ___  _ _ __   __ _  \ `--.  ___   ___  _ __\n| |    / _ \| '_ ` _ \| | '_ \ / _` |  `--. \/ _ \ / _ \| '_ \ \n| \__/\ (_) | | | | | | | | | | (_| | /\__/ / (_) | (_) | | | |\n \____/\___/|_| |_| |_|_|_| |_|\__, | \____/ \___/ \___/|_| |_|\n                                __/ |\n                               |___/ "
        textDs=" _____                 _\n/  __ \               (_)\n| /  \/ ___  _ __ ___  _ _ __   __ _\n| |    / _ \| '_ ` _ \| | '_ \ / _` |\n| \__/\ (_) | | | | | | | | | | (_| |\n \____/\___/|_| |_| |_|_|_| |_|\__, |\n      _____                     __/ |\n     /  ___|                    |___/\n     \ `--.  ___   ___  _ __\n      `--. \/ _ \ / _ \| '_ \ \n     /\__/ / (_) | (_) | | | |\n     \____/ \___/ \___/|_| |_|"
        bell = "   ___                                          _____\n .'   \   __.  , _ , _   ` , __     ___.       (        __.    __.  , __\n |      .'   \ |' `|' `. | |'  `. .'   `        `--.  .'   \ .'   \ |'  `.\n |      |    | |   |   | | |    | |    |           |  |    | |    | |    |\n  `.__,  `._.' /   '   / / /    |  `---|      \___.'   `._.'  `._.' /    |\n                                   \___/  "
        epic = " _______  _______  _______ _________ _        _______    _______  _______  _______  _\n(  ____ \(  ___  )(       )\__   __/( (    /|(  ____ \  (  ____ \(  ___  )(  ___  )( (    /|\n| (    \/| (   ) || () () |   ) (   |  \  ( || (    \/  | (    \/| (   ) || (   ) ||  \  ( |\n| |      | |   | || || || |   | |   |   \ | || |        | (_____ | |   | || |   | ||   \ | |\n| |      | |   | || |(_)| |   | |   | (\ \) || | ____   (_____  )| |   | || |   | || (\ \) |\n| |      | |   | || |   | |   | |   | | \   || | \_  )        ) || |   | || |   | || | \   |\n| (____/\| (___) || )   ( |___) (___| )  \  || (___) |  /\____) || (___) || (___) || )  \  |\n(_______/(_______)|/     \|\_______/|/    )_)(_______)  \_______)(_______)(_______)|/    )_)"
        return [textt, textSs, textGs, textIs, textD, textDs, bell, epic, ]
    


def Main():
    x = 0
    while x != ord('0'):
        screen.clear(); screen.border(0); screen.addstr(0, col-20, "console width = "+str(col));screen.addstr(0,2,"0 - Exit ");
        foo = ascii("logo"); bar = fitter(foo); bb = choice(bar); sentsplit(bb[0], 1, bb[1], 0.003); time.sleep(0.2); 
        screen.addstr(4, fitter("SpyCam!"), "SpyCam!"); time.sleep(0.2);
        st1 = "Enter a Number..."; st2 = "1 - Make Presence Known\n2 - Stream Camera\n3 - Stream Mic";
        sentsplit(st1, 6, fitter(st1), 0.01); sentsplit(st2, 8, fitter(st2), 0.01); #curses.noecho(); curses.cbreak();
        x = screen.getch()

#        if x != ord('0') or ord('1') or ord('2') or ord('3'):
#          rr = "Incorrect Input"; arr = fitter(rr);
#          sentsplit("Incorrect Input", 0, arr, 0.02); screen.addstr(0, arr, "-------------------");

        if x == ord('1'):
           y = 0;
           while y != ord('0'):
               k = 0; screen.clear(); screen.border(0);screen.addstr(0, 2, "0 - Previous");screen.addstr(0, col-20, "console width = "+str(col));
               vol = "dbus-send --print-reply --type=method_call --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer com.nokia.mafw.extension.get_extension_property string:volume|awk '/nt/ {print $3}'"
               p = commands.getoutput(vol)
               currvol = " Current System Volume:"+str(p)+" "
               sentsplit(currvol, 0, fitter(currvol), 0.01)
               st1 = "Pick a Phrase"; st2 = "1 - Change System Volume\n2 - 'Unauthorized usage of phone'\n3 - 'HELP HELP THIS PHONE IS STOLEN!'\n4 - Custom Phrase\n5 - Play sound from file.";
               sentsplit(st1, 3, fitter(st1), 0.02); sentsplit(st2, 5, fitter(st2), 0.01);
               y = screen.getch()
               while k!= -1:
                   if y == ord('1') : 
                        vvv = get_param("Set volume (0-100), currently :"+str(p))
                        execute_cmd("dbus-send --type=method_call --dest=com.nokia.mafw.renderer.Mafw-Gst-Renderer-Plugin.gstrenderer /com/nokia/mafw/renderer/gstrenderer com.nokia.mafw.extension.set_extension_property string:volume variant:uint32:"+str(vvv))
                        break

                   elif y == ord('5'):
                       z = 0
                       oo = "/home/user/MyDocs/.sounds/"
                       while z != ord('0'):
                           screen.clear(); screen.border(0);
                           screen.addstr(0, col-22, "console width="+str(col))
                           screen.addstr(2, 5, "Current directory:"+oo);screen.addstr(3, 8, "Press Enter to display");
                           input = screen.getstr(3, 30, 31); screen.addstr(3,8, "                           ");
                           screen.addstr(0, fitter("                    "), " 1 - Change Directory ")
                           lis = musicLib(3, 3, 0.05, oo)
                           m = 0
                           while m != -1:
                              z = screen.getch()
                              if z == ord('1'):
                                   screen.addstr(2, 5, "Change to:"+oo+"                 ")
                                   screen.addstr(0, 2, "type '..' to move up")
                                   oo = oo+screen.getstr(2, len(oo)+15, 60)
                                   oo = oo.replace(" ","\ "); oo = oo.replace("(","\(");oo = oo.replace(")","\)");
                                   if(oo.endswith('/')==False): oo = oo+"/"
                                   break
                              else:
                                   try:
                                       index = z-97; currfile = oo+lis[index]
                                   except IndexError:
                                       sentsplit("Error", 3, 3, 0.1)
                                       break

                                   currfile = currfile.replace(" ","\ "); currfile = currfile.replace("(","\(");currfile = currfile.replace(")","\)");
                                   curses.endwin(); execute_cmd("gst-launch-0.10 filesrc location="+currfile+" ! decodebin ! autoaudiosink", True)
                                   break
#                              break

                   elif y == ord('2') or ord('3') or ord('4'):
                       txt = ''
                       if y == ord('2'): txt = "Unauthorized usage of phone"
                       elif y == ord('3'): txt = "HELP HELP THIS PHONE IS STOLEN!"
                       elif y == ord('4'): txt = get_param("Enter Custom text:")
                       txt = '"'+txt+'"'
                       execute_cmd("espeak "+txt)
                       break
                   
#                   break 

                        
        if x == ord('2'):
            qbcam = 0
            width = 320
            height = 640
            screen.clear()
            screen.border(0)
            screen.addstr(0, col-22, "console width="+str(col));screen.addstr(0,2,"0 - Previous");
            st1 = "Front or Back?"
            st2 = "1 - Front 320x240\n2 - Back 320x240\n3 - Back 640x480"
            sentsplit(st1, 3, fitter(st1), 0.05)
            sentsplit(st2, 6, fitter(st2), 0.01)
            y = 0
            width = height = qbcam = 0 
            while y != ord('0'):
	        y = screen.getch()
                if y == ord('1') or ord('2'):
                    width = 320;height = 240
                    if y == ord('1'): qbcam = 1
                    elif y == ord('2'): qbcam = 0
                elif y == ord('3'):
                    width = 640;height = 480;qbcam = 0
                    
                comm = "gst-launch-0.10 v4l2src device=/dev/video" + str(qbcam) + " ! videoscale ! video/x-raw-yuv,width=" + str(width) + ",height=" + str(height) + "! xvimagesink"
                try:
		    execute_cmd(comm)
#                   led = commands.getoutput("dbus-send --system --type=method_call --dest=com.nokia.mce /com/nokia/mce/request com.nokia.mce.request.req_led_pattern_deactivate string:"PatternCommunicationIM")
                except KeyboardInterrupt:
		    execute_cmd("killall gst-launch-0.10")
		    curses.endwin(); exit();
            break
            
        if x == ord('3'):
            screen.clear();screen.border();floo = ascii("coming soon");blar = fitter(floo);bb = choice(blar)
            screen.addstr(0, col-20, "console width = "+str(col));sentsplit(bb[0], 5, bb[1], 0.003)
            time.sleep(1);cash = fitter("That's right folks....    wait for the update!")
            sentsplit("That's right folks....", 10, cash, 0.3, False);time.sleep(0.5)
            sentsplit("  wait for the update!", 10, cash+25, 0.05);time.sleep(2)

        
    execute_cmd("killall gst-launch-0.10")
    curses.endwin()
    exit()

screen = curses.initscr()
row = 0 ; col = 0;
conswidth()
try:
    if col<60:
        curses.endwin()
        print "Console width is "+str(col)+".\nPlease resize window to be 60 or larger"
        exit()
    else:
        curses.cbreak(); #curses.noecho();
        Main()

except KeyboardInterrupt:
    curses.endwin()
    exit()
except:
    raise
#    print sys.exc_info()[1]
