#!/usr/bin/env python
# -*- coding: utf-8 -*-


from __future__ import print_function
import base64
import logging

from keyring.errors import (PasswordDeleteError)
from keyring.backend import KeyringBackend
from botocore.exceptions import EndpointConnectionError
import boto3facade.s3
import string
import six
import keyring
import sys

from s3keyring.settings import config

# Python2/3 compatibility
if sys.version_info.major == 2:
    from base64 import decodestring as base64_decode
    from base64 import encodestring as base64_encode
elif sys.version_info.major == 3:
    from base64 import decodebytes as base64_decode
    from base64 import encodebytes as base64_encode
else:
    raise Exception("Invalid Python major version: {}".format(sys.version_info.major))


LEGAL_CHARS = (
    getattr(string, 'letters', None)     # Python 2.x
    or getattr(string, 'ascii_letters')  # Python 3.x
    ) + string.digits + '/_-'

ESCAPE_FMT = "_{}02X"

logger = logging.getLogger()
logger.setLevel("INFO")


class PasswordGetError(Exception):
    """Raised when there is an error retrieving a password.
    """
    pass


class InitError(Exception):
    """Raised when the S3 backend has not been properly initialized
    """
    pass


class S3Backed(object):
    def __init__(self, config_file=None):
        """Initialize the keyring."""

        if config_file:
            config.boto_config.config_file = config_file
            config.boto_config.load()

        self.s3 = boto3facade.s3.S3(config=config.boto_config)

    @property
    def bucket(self):
        return self.s3.resource.Bucket(config.profile["bucket"])

    def supported(self):
        try:
            resp = self.s3.client.list_objects(Bucket=self.bucket.name)
            return resp['ResponseMetadata']['HTTPStatusCode'] == 200
        except:
            return False

    @property
    def kms_key_id(self):
        return config.profile["kms_key_id"]

    @property