#
# Copyright (c) SAS Institute Inc.
#
# 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.
#


import copy
from testrunner import testhelp
import tempfile
import random
import string
import subprocess
import os
import sys
import StringIO

from testutils import mock


from mint_rephelp import MINT_HOST, MINT_DOMAIN, MINT_PROJECT_DOMAIN
from mint_rephelp import resetCache
from mint_test import resources

import mint.db.database
from mint import shimclient
from mint import config
from mint import buildtypes
from mint.flavors import stockFlavors
from mint import server
from mint import userlevels
from mint.lib.data import RDT_STRING

from conary import dbstore
from conary.deps import deps
from conary.lib import util
from testutils import sqlharness

from rpath_proddef import api1 as proddef
from proddef_test import resources as proddef_resources


def stockBuildFlavor(db, buildId, arch = "x86_64"):
    cu = db.cursor()
    flavor = deps.parseFlavor(stockFlavors['1#' + arch]).freeze()
    cu.execute("UPDATE Builds set troveFlavor=? WHERE buildId=?", flavor, buildId)
    db.commit()


class FixtureCache(object):
    _fixtures = {}

    def list(self):
        fixtureNames = [x for x in self.__class__.__base__.__dict__ \
                        if x.startswith('fixture')]
        return dict([(x.replace('fixture', ''),
                      self.__getattribute__(x).__doc__) for x in fixtureNames])

    def loadFixture(self, key, loadFn=None):
        if not loadFn:
            name = 'fixture' + key
            loadFn = self.__getattribute__(name)
        if key not in self._fixtures:
            self._fixtures[key] = loadFn(self.newMintCfg(key))
        return self._fixtures[key]

    def load(self, name, loadFn=None):
        raise NotImplementedError

    def newMintCfg(self, name):
        # IDEA: If fixtures did things differently
        # and instead of creating a new config for you
        # to use just used the existing config
        # and froze at the end, we could stack
        # fixtures, making them less expensive to create.
        cfg = config.MintConfig()
        cfg.authUser = 'mintauth'
        cfg.authPass = 'mintpass'
        cfg.debugMode = True
        cfg.namespace = 'yournamespace'