import os, docker as Docker

docker = Docker.from_env()

class BaseDockerModel(object):
    def __init__(self, imageName, imageTag="latest"):
        image = "{0}:{1}".format(imageName, imageTag)
        image = docker.images.list(image)
        self.image = image[0] if len(image) > 0 else None
        self.name = ""
        self.container = None
    def isExist(self):
        filters = { "name": self.name }
        containers = docker.containers.list(all=True, filters=filters)
        return len(containers) > 0
    def isRunning(self):
        return self.container.status == "running" if self.container is not None else False
    def isExited(self):
        return self.container.status == "exited" if self.container is not None else False
    def Build(self, imageName, imageTag="latest"):
#        try:
            imagePath = "{0}/containers/{1}".format(os.path.dirname(__file__), imageName)
            image = "{0}:{1}".format(imageName, imageTag)
#             print(imagePath)
            self.image = docker.images.build(path=imagePath, tag=imageName)[0]
            return True
#        except:
#            return False
    def Start(self):
        try:
            self.container.start()
            return True
        except:
            return False
    def Stop(self):
        try:
            self.container.stop()
            return True
        except:
            return False
    def Remove(self):
        try:
            self.container.stop()
            self.container.remove()
            return True
        except:
            return False
class RTMPDockerModel(BaseDockerModel):
    def __init__(self, ID):
        super().__init__('rtmp_deliver')
        self.name = "{0}_rtmp_deliver".format(ID)
    def Build(self):
        return super().Build('rtmp_deliver')
    def Run(self, in_host, in_port, in_key, out_host, out_port, out_key):
        if not self.isExist():
            environment = {
                "RTSP_HOST": in_host,
                "RTSP_PORT": in_port,
                "RTSP_KEY": in_key,
                "RTMP_HOST": out_host,
                "RTMP_PORT": out_port,
                "RTMP_KEY": out_key
            }
            try:
                run = docker.containers.run(
                    self.image, 
                    name = self.name, 
                    environment = environment,
                    remove = True,
                    detach = True,
                    links = { "srs": "srs" }
                )
                self.container = docker.containers.get(self.name)
                return True
            except:
                return False
        else:
            self.container = docker.containers.get(self.name)
            return True
        return True
