﻿using BaxterWorks.B2.Exceptions;
using BaxterWorks.B2.Types;

namespace BaxterWorks.B2.Extensions
{
    public static class BucketExtensions
    {
        public static Bucket GetOrCreateBucket(this ServiceStackB2Api client, CreateBucketRequest request) 
        {
            try
            {
                return client.CreateBucket(request);
            }
            catch (DuplicateBucketException) //todo: there are other ways this could fail
            {
                return client.GetBucketByName(request.BucketName);
            }
        }

        /// <summary>
        /// Get an existing bucket, or create a new one if it doesn't exist. Defaults to a private bucket
        /// </summary>
        /// <param name="client"></param>
        /// <param name="bucketName"></param>
        /// <returns><see cref="Bucket"/></returns>
        public static Bucket GetOrCreateBucket(this ServiceStackB2Api client, string bucketName)
        {
            try
            {
                return client.CreateBucket(bucketName);
            }
            catch (DuplicateBucketException) //todo: there are other ways this could fail
            {
                return client.GetBucketByName(bucketName);
            }
        }

        public static Bucket OverwriteBucket(this ServiceStackB2Api client, CreateBucketRequest request, bool deleteFiles = false)
        {
            try
            {
                return client.CreateBucket(request);
            }
            catch (DuplicateBucketException) //todo: there are other ways this could fail
            {
                Bucket targetBucket = client.GetBucketByName(request.BucketName);
                if (deleteFiles)
                {
                    client.DeleteBucketRecursively(targetBucket);
                }
                else
                {
                    client.DeleteBucket(targetBucket);
                }

                return client.CreateBucket(request);
            }
        }
    }
}