# coding: utf-8
'''
Created on 20 февр. 2016 г.

@author: popov_v
'''

import tornado.ioloop
import tornado.web
import tornado.httpserver
import ssl
import httplib
import argparse

class TestConnection(tornado.web.RequestHandler):
    u'''Проверка соединения с ФРМР.'''
    
    def initialize(self, cafile, certfile):
        self.context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=cafile)
        self.context.set_ciphers('GOST2001-GOST89-GOST89')
        self.context.load_cert_chain(certfile=certfile, keyfile=certfile)
        self.conn = httplib.HTTPSConnection(host="service.rosminzdrav.ru", port=443,
                                 context=self.context)
        #self.conn.connect()
        self.bodymsg = u'''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                                                     xmlns:med="http://service.rosminzdrav.ru/MedStaff">
                                                      <soapenv:Header />
                                                      <soapenv:Body>
                                                        <med:TestConnection />
                                                      </soapenv:Body>
                                                    </soapenv:Envelope>'''
    
    def get(self):
        
        self.conn.request("POST", "/MedStaff/Service.svc/basic",
                      headers={'SOAPAction': 'http://service.rosminzdrav.ru/MedStaff/IService/TestConnection',
                                'Content-Type': 'text/xml; charset=utf-8'},
                      body=self.bodymsg)
        r = self.conn.getresponse()

        self.write(r.read())
        
    def on_finish(self):
        
        self.conn.close()
        
class GetEmployee(tornado.web.RequestHandler):
    u'''Получение данных ФЛ из ФРМР.'''
    
    def initialize(self, cafile, certfile):
        self.context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=cafile)
        self.context.set_ciphers('GOST2001-GOST89-GOST89')
        self.context.load_cert_chain(certfile=certfile, keyfile=certfile)
        self.conn = httplib.HTTPSConnection(host="service.rosminzdrav.ru", port=443,
                                 context=self.context)
        #self.conn.connect()

    def get(self, snils):
        
        self.bodymsg = u'''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:med="http://service.rosminzdrav.ru/MedStaff">
                          <soapenv:Header />
                          <soapenv:Body>
                            <med:GetEmployee>
                              <med:value>%s</med:value>
                            </med:GetEmployee>
                          </soapenv:Body>
                        </soapenv:Envelope>''' % snils
        self.conn.request("POST", "/MedStaff/Service.svc/basic",
                      headers={'SOAPAction': 'http://service.rosminzdrav.ru/MedStaff/IService/GetEmployee',
                                'Content-Type': 'text/xml; charset=utf-8'},
                      body=self.bodymsg)
        r = self.conn.getresponse()

        self.write(r.read())
        
    def on_finish(self):
        
        self.conn.close()

if __name__ == "__main__":
    
    #cafile = '/mnt/hgfs/frmr/mz_root.pem'
    #certfile = '/mnt/hgfs/frmr/mz_popov_nop.pem'
    
    parser = argparse.ArgumentParser()
    parser.add_argument("-p", "--port", dest='port', type=int,
                    help="port of web server instance")
    parser.add_argument("--cafile", dest='cafile', type=str,
                    help="CA file path. Must be in PEM format.")
    parser.add_argument("--certfile", dest='certfile', type=str,
                    help="Certificate file path. Must be in PEM format and contains cert and key.")
    args = parser.parse_args()
    
    application = tornado.web.Application([
        (r"/TestConnection", TestConnection,
          dict(cafile=args.cafile, certfile=args.certfile)),
        (r"/GetEmployee/(.*)", GetEmployee,
         dict(cafile=args.cafile, certfile=args.certfile)),
    ])
    #application.listen(args.port)
    # simple single-process:
    server = tornado.httpserver.HTTPServer(application)
    server.listen(args.port)
    tornado.ioloop.IOLoop.current().start()