#!/home/qdot/venvs/bp/bin/python
import sys
sys.path.append("/home/qdot/code/git-projects/buttplug/")
import os
import tempfile
import shutil
from buttplug.template.plugin import BPPlugin


class TestPlugin(BPPlugin):
    APP_NAME = "Test Plugin"
    APP_DESC = "Test for BP Server Plugin System"

    def __init__(self):
        super(TestPlugin, self).__init__()
        self.add_handlers({"BPPluginDeviceList": self.send_device_list_msg,
                           "RawTestMsg": self.raw_test_msg})
        self.device_id = None

        self.device_types = ["TestSuccessfulOpen",
                             "TestDroppedSocket",
                             "TestInvalidDevice",
                             "TestOpenTimeout",
                             "TestPingTimeout",
                             "TestRandomClose"]
        self.device_file_name = None

    def release_device(self, msg):
        if self.device_file_name is not None:
            os.unlink(self.device_file_name)

    def send_device_list_msg(self, msg):
        self.send(["s", "BPPluginDeviceList", self.get_device_list()])

    def get_device_list(self):
        """Returns the device list for the plugin"""
        return self.device_types

    def raw_test_msg(self, msg):
        (from_addr, msg_type, msg_payload) = msg
        self.send(["c", "RawTestMsg", msg_payload.swapcase()])

    def open_device(self, msg):
        (from_addr, msg_type, device_name) = msg
        self.device_file_name = os.path.join(tempfile.gettempdir(), "fe-%s" % (device_name))
        if os.path.exists(self.device_file_name):
            self.send(["s", "BPPluginOpenDevice", device_name, False])
            return
        open(self.device_file_name, "w").close()
        self.send(["s", "BPPluginOpenDevice", device_name, True])

def main():
    """Main function for BP Plugin"""
    t = TestPlugin()
    return t.run()


if __name__ == '__main__':
    sys.exit(main())
