#!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Simplified chat demo for websockets.

Authentication, error handling, etc are left as an exercise for the reader :)
"""

import logging
import tornado.escape
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
import uuid

from tornado.options import define, options

define("port", default=8888, help="run on the given port", type=int)


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", LeviTestHandler),
        ]
        tornado.web.Application.__init__(self, handlers)


class LeviTestHandler(tornado.websocket.WebSocketHandler):
    waiters = set()

    def open(self):
        LeviTestHandler.waiters.add(self)

    def on_close(self):
        LeviTestHandler.waiters.remove(self)

    @classmethod
    def send_updates(cls, chat):
        logging.info("sending message to %d waiters", len(cls.waiters))
        for waiter in cls.waiters:
            try:
                waiter.write_message(chat)
            except:
                logging.error("Error sending message", exc_info=True)

    def on_pong(self, data):
        print id(self)
        print data

    def build(self):
        msg ={
                "name": "nbetest",
                "uid": 4011,
                "id": str(uuid.uuid4()),
                "tasks":{
                    "build": [
                        {
                            "id": 123,
                            "group":"platform",
                            "name":"nbetest",
                            "version":"18e02fa",
                            "base":"docker-registry.intra.hunantv.com/nbeimage/ubuntu:python-2014.9.30",
                            "build":"pip install -r requirements.txt",
                        },
                    ],
                }
        }
        LeviTestHandler.send_updates(msg)

    def test(self):
        msg = {
                "name": "nbetest",
                "uid": 4011,
                "id": str(uuid.uuid4()),
                "tasks":{
                    "add": [{
                        "id": 456,
                        "version": "18e02fa",
                        "cmd": ["python", "xxx.py"],
                        "memory": 4294967296,
                        "cpuset": "0",
                        "cpushares": 512,
                        "test": "2266c74",
                    }],
              }
        }
        LeviTestHandler.send_updates(msg)

    def add(self):
        msg = {
                "name": "nbetest",
                "uid": 4011,
                "id": str(uuid.uuid4()),
                "type": 1,  # add
                "tasks":{
                    "add":[{
                        "id": 789,
                        "version": "18e02fa",
                        "cmd": ["python", "app.py"],
                        "memory": 4294967296,
                        "cpuset": "0",
                        "cpushares": 512,
                        "daemon": "2266c75",
                    },
                    {
                        "id": 012,
                        "version": "18e02fa",
                        "cmd": ["python", "app.py"],
                        "memory": 4294967296,
                        "cpuset": "0",
                        "cpushares": 512,
                        "bind": 49072,
                        "port": 5000,
                    }],
                },
        }
        LeviTestHandler.send_updates(msg)

    def report(self):
        msg = {
                "id": str(uuid.uuid4()),
                "info": True,
        }
        LeviTestHandler.send_updates(msg)

    def delete(self, cid):
        msg = {
                "name": "nbetest",
                "uid": 4011,
                "id": str(uuid.uuid4()),
                "tasks":{
                    "remove":[{
                        "id": 011,
                        "container": cid,
                        "rmimage": False,
                    }]
                }
        }
        LeviTestHandler.send_updates(msg)

    def update(self, cid):
        msg = {
                "name": "nbetest",
                "uid": 4011,
                "id": str(uuid.uuid4()),
                "tasks":{
                    "update":[{
                        "container": cid,
                        "id": 013,
                    }]
                }
        }
        LeviTestHandler.send_updates(msg)

    def on_message(self, message):
        logging.info("got message %r", message)
        if message == "add":
            self.add()
        elif message.startswith("del"):
            m = message.split(" ", 2)[1]
            self.delete(m)
        elif message.startswith("update"):
            m = message.split(" ", 2)[1]
            self.update(m)
        elif message == "build":
            self.build()
        elif message == "test":
            self.test()
        elif message == "report":
            self.report()
        else:
            return

def main():
    tornado.options.parse_command_line()
    app = Application()
    app.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()
