#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# vim: expandtab sw=4 ts=4 sts=4:
#
# Copyright © 2003 - 2017 Michal Čihař <michal@cihar.com>
#
# This file is part of python-gammu <https://wammu.eu/python-gammu/>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
'''
Service numbers dialogue example.
'''

from __future__ import print_function
import gammu
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import time

REPLY = False

gsm = (u"@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞ\x1bÆæßÉ !\"#¤%&'()*+,-./0123456789:;<=>"
       u"?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑÜ§¿abcdefghijklmnopqrstuvwxyzäöñüà")

def gsm7bitdecode(f):
   f = ''.join(["{0:08b}".format(int(f[i:i+2], 16)) for i in range(0, len(f), 2)][::-1])
   return ''.join([gsm[int(f[::-1][i:i+7][::-1], 2)] for i in range(0, len(f), 7)])

def gsm7bitencode(src):
	result, count, last = [], 0, 0
	for c in src:
		this = ord(c) << (8 - count)
		if count:
			result.append('%02X' % ((last >> 8) | (this & 0xFF)))
		count = (count + 1) % 8
		last = this
	result.append('%02x' % (last >> 8))
	return ''.join(result)

def callback(state_machine, callback_type, data):
    '''
    Callback on USSD data.
    '''
    global REPLY
    if callback_type != 'USSD':
        print('Unexpected event type: {0}'.format(callback_type))
        sys.exit(1)

    REPLY = True

    #print('Network reply:')
    #print('Status: {0}'.format(data['Status']))
    #print(data['Text'])
    print(gsm7bitdecode(data['Text']))

    if data['Status'] == 'ActionNeeded':
        do_service(state_machine)


def init():
    '''
    Intializes gammu and callbacks.
    '''
    state_machine = gammu.StateMachine()
    state_machine.ReadConfig()
    state_machine.Init()
    state_machine.SetIncomingCallback(callback)
    try:
        state_machine.SetIncomingUSSD()
    except gammu.ERR_NOTSUPPORTED:
        print('Incoming USSD notification is not supported.')
        sys.exit(1)
    return state_machine


def do_service(state_machine):
    '''
    Main code to talk with worker.
    '''
    global REPLY

    if len(sys.argv) >= 2:
        code = sys.argv[1]
        del sys.argv[1]
    else:
        prompt = 'Enter code (empty string to end): '
        try:
            code = raw_input(prompt)
        except NameError:
            code = input(prompt)
    code=gsm7bitencode(code)
    #print(code)
    if code != '':
        #print('Talking to network...')
        REPLY = False
        state_machine.DialService(code)
        loops = 0
        while not REPLY and loops < 10:
            #print("Loop")
            state_machine.ReadDevice()
            time.sleep(1)
            loops += 1


def main():
    state_machine = init()
    do_service(state_machine)
    state_machine.Terminate()


if __name__ == '__main__':
    main()

