#!/usr/bin/python3
import os, sys, configparser, requests, locale
import gi 
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
from locale import gettext as _

DOMAIN = 'registrar'
LOCALE_DIR = '/usr/share/locale'
locale.bindtextdomain(DOMAIN, LOCALE_DIR)
locale.textdomain(DOMAIN)

RosaServiceId = "20713"
RosaKey = '044cf13c07ee062c0f38e61bd341b912065cc5bb1403e625e62c05e1adadc924aa7cffa0aee5d3ddabb60ca0403df4feab7c5a4e3b2a61ab3a011cd3f90bdc3db2'

def message( first, second, mtype='info'):
    if mtype == 'info':
        mtype = Gtk.MessageType.INFO
    elif mtype == 'error':
        mtype = Gtk.MessageType.ERROR
    messagedialog = Gtk.MessageDialog(transient_for=window,
						destroy_with_parent=True,
						modal=True,
						message_type=mtype,
						buttons=Gtk.ButtonsType.OK,
						text=first)
    messagedialog.format_secondary_text(second)
    response = messagedialog.run()
    if response == Gtk.ResponseType.OK or response == Gtk.ResponseType.DELETE_EVENT:
        messagedialog.destroy()

if os.path.exists('./registrar.ini'):
    config = './registrar.ini'
elif os.path.exists('/etc/registrar.ini'):
    config = '/etc/registrar.ini'

if config:
    cfg = configparser.ConfigParser()
    cfg.read(config)

if 'REGISTRAR' in cfg:
    if 'URL' in cfg['REGISTRAR']:
        URL = cfg['REGISTRAR']['URL']

try:
    with open('/etc/machine-id', 'r') as fmachine:
        for line in fmachine.readlines():
            if len(line.strip()) == 32:
                machine_id = line.strip()
                break 
except:
    print('cannot get machine_id')
    quit()

orderid_suffix = machine_id[0:8]

response =  requests.get(URL + 'status.py', 
            params=[ ( 'machine_id', machine_id ),
            ( 'counter', 1 ) ] )
registrated = False
stdcost = False
extcost = False
if response.status_code == 200:
    retdict = {}
    for a in response.text.split('\n'):
        if a.startswith('<') or not a.strip():
            continue
        retdict[a.split(':')[0]] = a.split(':')[1]
        if 'counter' in retdict.keys():
            registrated = True
        if 'stdcost' in retdict.keys():
            stdcost = retdict['stdcost']
        if 'extcost' in retdict.keys():
            extcost = retdict['extcost']

if not registrated:
    message(_('Need registration'), _('Please registrate OS for your machine, and run program again'), 'error')
    if len(sys.argv) == 1:
        os.execl('/usr/bin/registrar', 'registrar')
    else:
        quit()
if not stdcost:
    message(_('Error'), _('The program is unable to get supports cost'), 'error')
    quit()

def header(header):
    return """
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru-ru" lang="ru-ru" >
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>%s</title>
<style>
    body {
    background-image: linear-gradient(to top right, #004465, #002b43);
    font-family: arial;
    height: 100vh;
    }
    a {
    outline: none;
    text-decoration: none;
    }
    a:link {
    color: white;
    text-decoration: none;
    }
    a:visited {
    color: white;
    text-decoration: none;
    }
    a:hover {
    color: white;
    font-size: xxx-large;
    }
    a:active {
    color: white;
    font-size: xxx-large;
    text-decoration: underline;
    }
    .text {
    color: white;
    text-align:  center;
    margin-top: 10%%;
    }
    .center {
    color: white;
    text-align:  center;
    font-size: xx-large;
    margin-top: 5%%;
    }
    .btn {
    color: #004465;
    text-align:  center;
    font-size: xx-large;
    border-radius: 0.3em;
    margin-top: 5%%;
    }
    
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="https://widget.payselection.com/lib/pay-widget.js"></script>
</head><body>""" % ( header )

def print_script():
    return """
<script>
function generate(n) {
        var add = 1, max = 12 - add;   // 12 is the min safe number Math.random() can generate without it starting to pad the end with zeros.   
        
        if ( n > max ) {
                return generate(max) + generate(n - max);
        }
        
        max        = Math.pow(10, n+add);
        var min    = max/10; // Math.pow(10, n) basically
        var number = Math.floor( Math.random() * (max - min + 1) ) + min;
        
        return ("" + number).substring(add); 
}

const url = 'https://webform.payselection.com/webpayments/create';
var d = new Date,
    dformat = d.toLocaleDateString('ru-RU')+' '+
              [d.getHours(),
               d.getMinutes(),
               d.getSeconds()].join(':');

this.pay = function() {
    var amount = "%s"
    var support = "standard"
    if (document.getElementById("select") !== null) {
        let select = document.getElementById("select");
        if ( select.value == '1' ) {
            var amount = "%s"
            var support = "standard"
        } else {
            var amount = "%s"
            var support = "extended"
        }
    }

    var orderid = ['%s', generate(6)].join('-')
    var widget = new pw.PayWidget();
    console.log("PAY");// вызов метода одностадийной оплаты
    widget.pay(
    {
     serviceId: "%s",
     key: "%s",
     logger:true,
  },
     {
      MetaData: {
        PaymentType: "Pay",
     },
      PaymentRequest: {
         OrderId: orderid,
         Amount: amount ,
         Currency: "RUB",
         Description: "Rosa support",
         ExtraData: {
             "MachineId": "%s", 
             "Days": "365",
             "Support": support, 
             "ReturnUrl": "https://rosalinux.ru",
             "WebhookUrl": "https://aisuld.rosalinux.ru/cgi-bin/webhook.py",
         }
     },
   },
   {
     onSuccess: function(res) {
       console.log("onSuccess from shop", res);
     }, 
<!-- PAY_WIDGET:CLOSE_AFTER_SUCCESS -->
    onError: function(res) {
       console.log("onFail from shop", res);
    }, 
<!-- PAY_WIDGET:CREATE_NETWORK_ERROR, PAY_WIDGET:CREATE_BAD_REQUEST_ERROR, PAY_WIDGET:CLOSE_AFTER_FAIL,PAY_WIDGET:CLOSE_AFTER_CREATE_NETWORK_ERROR, PAY_WIDGET:CREATE_BAD_REQUEST_ERROR   
-->
     onClose: function(res) {
       console.log("onClose from shop", res);
     }, 
   },
  );
}; 
</script>
""" % (str(stdcost), str(stdcost), str(extcost), orderid_suffix, RosaServiceId, RosaKey, machine_id )
if not os.path.exists('/tmp/registrar'):
    os.mkdir('/tmp/registrar')
with open('/tmp/registrar/payment.html', 'w') as f:
    print(header(_('Payment for support')), file=f)
    print(print_script(), file=f)
    if extcost:
    # С выбором расширенной поддержки
        print('''
    <p class=text><img src="/usr/share/registrar/rosa_logo_white.svg" width=200></p>
    <div class="center"><p><a href="https://www.rosalinux.ru/support" target="_blank">%s</a></p>
    <p>%s:  <select class='btn' name="select" id="select">
    <option value='1'>%s</option>
    <option value='2'>%s</option>
    </select>
    <button class='btn' onclick="pay()">%s</button></div>
    <p class="text"> Machine-id: %s </p>
  </p>
''' % (_("Rosa technical support for 365 days"),_('Support'), _('Standard'), _('Extended'), _('Pay'), machine_id)
, file=f)
    else:
        print('''
    <p class=text><img src="/usr/share/registrar/rosa_logo_white.svg" width=200></p>
    <div class="center"><p><a href="https://www.rosalinux.ru/support" target="_blank">%s</a></p>
    <p><button class='btn' onclick="pay()">%s</button></p></div>
    <p class="text"> Machine-id: %s </p>
    </p>
''' % (_("Rosa technical support for 365 days"), _('Pay'), machine_id)
, file=f)


messagedialog = Gtk.MessageDialog(destroy_with_parent=True,
                    modal=True,
                    message_type=Gtk.MessageType.ERROR,
                    buttons=Gtk.ButtonsType.OK,
                    text=_('Rosa linux support'))
messagedialog.format_secondary_text(_('You can pay for support on the page \n that opens in the browser after clicking OK'))
response = messagedialog.run()
if response == Gtk.ResponseType.OK or response == Gtk.ResponseType.DELETE_EVENT:
    messagedialog.destroy()
os.execl('/usr/bin/xdg-open', 'xdg-open', '/tmp/registrar/payment.html' )
