#!/usr/bin/python

import sys
import yaml
import time
from bamboo_api import BambooAPIClient
from git import Repo



class Business(object):
    def __init__(self, build_file):
        self.pip = ""
        self.build_file = build_file
        self.config = ""

    def _parse_config_yml(self):
        """
        Parse the main config file
        """
        with open('config.yml', 'r') as stream:
            try:
                self.config = yaml.load(stream)
            except yaml.YAMLError as exc:
                print(exc)
                sys.exit(1)

    def _parse_build_yml(self):
        """
        Attempt to parse STDIN then if that fails attempt to 
        parse the first argument as a file name
        """
        with open(self.build_file, 'r') as stream:
            try:
                self.pipe = yaml.load(stream)
            except yaml.YAMLError as exc:
                print(exc)
                sys.exit(1)

    def _preflight(self):
        self.bamboo = BambooAPIClient(user=self.config['bamboo']['username'], 
                                      password=self.config['bamboo']['password'],
                                      host=self.config['bamboo']['hostname']) 

    def bambooBuildAndWait(self, waiting_queue):
        """
        Queue up bamboo build jobs 
        """
        build_queue = []

        if type(waiting_queue) != list:
            waiting_queue = [waiting_queue]

        for item in waiting_queue:
            print 'adding to queue', item
            build_key = self.bamboo.queue_build(item)['buildResultKey']
            build_queue.append(build_key)
            waiting_queue.remove(item)

        while len(build_queue) > 0:
            for item in list(build_queue):
                state = self.bamboo.get_results(item)['lifeCycleState']
                print item, state
                if state == 'Finished': 
                    build_queue.remove(item)
            time.sleep(1)


    def bashRunCommand(self):
        """
        Run a command using the bash shell
        """
        pass

    def bashRunFile(self, file_location):
        """
        Run a bash file using the bash shell
        """
        pass

    def gitClone(self, url):
        """
        Clone a git repository
        """
        pass

    def gitCreateTag(self, dir_location, tag):
        """
        Create an annotated git tag
        """
        pass


    def run(self):
        """
        Main entry point
        """
        self._parse_config_yml()
        self._parse_build_yml()
        self._preflight()
        for segment in self.pipe:
            print self.pipe
            for key, value in segment.iteritems():
                getattr(self, key)(value['jobs'])



if __name__ == '__main__':
    if len(sys.argv) != 2:
        print "Please provide a pipectl yaml file"
        sys.exit()
    Business(sys.argv[1]).run()


