public static ContentItem ToContentItem(this TreeItem treeItem)
        {
            var retVal = new ContentItem
                     {
                         Name = Path.GetFileNameWithoutExtension(treeItem.Path),
                         Path = treeItem.Path
                     };

            return retVal;
        }
        public static ContentItem ToDomainModel(this Models.ContentItem item)
        {
            var retVal = new ContentItem();

			retVal.CreatedDate = DateTime.UtcNow;
            retVal.Name = item.Name;
            retVal.Path = item.Path;
            
            return retVal;
        }
		public Task<ContentItem> GetContentItem(string path)
		{
			var retVal = new ContentItem();

			var fullPath = this.GetFullPath(path);

			var itemName = Path.GetFileName(fullPath);
			retVal.ByteContent = File.ReadAllBytes(fullPath);
			retVal.Name = itemName;
			retVal.Path = path;

			return Task.FromResult(retVal);
		}
        public ContentItem GetContentItem(string path)
        {
            var retVal = new ContentItem();

            var fullPath = this.GetFullPath(path);

            var itemName = Path.GetFileName(fullPath);
            retVal.ByteContent = File.ReadAllBytes(fullPath);
            retVal.Name = itemName;
            retVal.Path = path;

            return retVal;
        }
        public static ContentItem ToContentItem(this RepositoryContentInfo repositoryContent)
        {
            ContentItem retVal = null;

            if (repositoryContent.Type == ContentType.File)
            {
                retVal = new ContentItem();
                retVal.Name = repositoryContent.Name;
                retVal.Path = repositoryContent.Path;
            }

            return retVal;
        }
        public void Can_content_create_new_template_file(string repositoryType)
        {
            var repository = GetRepository(repositoryType);

            var contentItem = new ContentItem();
            contentItem.Id = Guid.NewGuid().ToString();
            contentItem.ByteContent = Encoding.UTF8.GetBytes("test");;
            contentItem.ContentType = "text/html";
            contentItem.Path = "default/template/testtemplate.html";
            contentItem.Path = string.Format("{0}/{1}", "teststore", contentItem.Path);
            contentItem.CreatedDate = DateTime.UtcNow;
            contentItem.ModifiedDate = DateTime.UtcNow;

            repository.SaveContentItem(contentItem.Path, contentItem);
            repository.DeleteContentItem(contentItem.Path);
        }
		public async Task<ContentItem> GetContentItem(string path)
		{
			var fullPath = GetFullPath(path);

			var retVal = new ContentItem();
			var result = await this._client.Repository.Content.GetContents(this._ownerName, this._repositoryName, fullPath);

			var item = result.SingleOrDefault();
			if (item != null)
			{
				retVal = item.ToContentItem();
				retVal.Path = path;
			}

			return retVal;
		}
        public async Task<ContentChangeSet> CreateFile(string relativePath, ContentItem item)
        {
            var fullPath = GetFullPath(relativePath);

            var response = await
                this._client.Repository.Content.CreateFile(
                    this._ownerName,
                    this._repositoryName,
                    fullPath,
                    new CreateFileRequest(string.Format("Create {0}", relativePath), Encoding.UTF8.GetString(item.ByteContent)));

            var createdItem = response.Content.ToContentItem();
            createdItem.Path = relativePath;

            var changeSet = new ContentChangeSet(response.Commit.Sha, new[] { new ContentItemInfo(createdItem) });
            return changeSet;
        }
        public void Can_content_save_delete_repositoryitems(string repositoryType)
        {
            var repository = GetRepository(repositoryType);

            var content = new ContentItem();
            content.ByteContent = Encoding.UTF8.GetBytes("Some new stuff");
            content.Path = "new/new123.liquid";
            content.CreatedDate = DateTime.UtcNow;
            content.Id = Guid.NewGuid().ToString();
            content.Name = "new123.liquid";

            var path = "Apple/Simple/new/new123.liquid";

            repository.SaveContentItem(path, content);

            var items = repository.GetContentItems("Apple/Simple", new GetThemeAssetsCriteria() { LoadContent = true, LastUpdateDate = DateTime.UtcNow.AddDays(-5) });

            Assert.Equal(items.Count(), 1);

            var item = repository.GetContentItem("Apple/Simple/new/new123.liquid");

            Assert.True(Encoding.UTF8.GetString(item.ByteContent).Contains("Some"));

            content = new ContentItem();
            content.ByteContent = Encoding.UTF8.GetBytes("Some new stuff. Changes");
            path = "Apple/Simple/new/new123.liquid";

            repository.SaveContentItem(path, content);

            items = repository.GetContentItems("Apple/Simple", new GetThemeAssetsCriteria() { LoadContent = true, LastUpdateDate = DateTime.UtcNow.AddDays(-5) });

            Assert.Equal(items.Count(), 1);

            item = repository.GetContentItem("Apple/Simple/new/new123.liquid");

            Assert.True(Encoding.UTF8.GetString(item.ByteContent).Contains("Some") && Encoding.UTF8.GetString(item.ByteContent).Contains("Changes"));

            path = "Apple/Simple/new/new123.liquid";

            repository.DeleteContentItem(path);

            items = repository.GetContentItems("Apple/Simple", new GetThemeAssetsCriteria() { LoadContent = true, LastUpdateDate = DateTime.UtcNow.AddDays(-5) });

            Assert.Equal(items.Count(), 0);
        }
		public static ContentItem ToContentItem(this RepositoryContent repositoryContent)
		{
			ContentItem retVal = null;

			if (repositoryContent.Type == ContentType.File)
			{
				retVal = new ContentItem();

				if (!string.IsNullOrEmpty(repositoryContent.Content))
				{
					retVal.ByteContent = Encoding.UTF8.GetBytes(repositoryContent.Content);
				}
				retVal.Name = repositoryContent.Name;
				retVal.Path = repositoryContent.Path;
			}

			return retVal;
		}
        public async void Can_content_create_new_template_file(string repositoryType)
        {
            var repository = GetRepository(repositoryType);

            var contentItem = new ContentItem
                              {
                                  Id = Guid.NewGuid().ToString(),
                                  ByteContent = Encoding.UTF8.GetBytes("test"),
                                  ContentType = "text/html",
                                  Path = "default/template/testtemplate.html"
                              };

            contentItem.Path = string.Format("{0}/{1}", "teststore", contentItem.Path);
            contentItem.CreatedDate = DateTime.UtcNow;
            contentItem.ModifiedDate = DateTime.UtcNow;

            var changeSet = await repository.CreateFile(contentItem.Path, contentItem);
            var createdItem = await repository.GetContent(changeSet.Items[0].ContentItem.Path);

            await repository.DeleteFile(contentItem.Path);
        }
        public async Task<ContentItem> GetContent(string relativePath)
        {
            var fullPath = GetFullPath(relativePath);

            var result = await GetAllContents(fullPath);

            if (result == null)
            {
                return null;
            }

            var retVal = new ContentItem();
            var item = result.SingleOrDefault();
            if (item != null)
            {
                retVal = item.ToContentItem();
                retVal.Path = relativePath;
            }

            return retVal;
        }
        public ContentItem GetContentItem(string path)
        {
            var fullPath = GetFullPath(path);

            var retVal = new ContentItem();

            var result = GetAllContents(fullPath);

            if (result == null)
            {
                return null;
            }

            var item = result.SingleOrDefault();
            if (item != null)
            {
                retVal = item.ToContentItem();
                retVal.Path = path;
            }

            return retVal;
        }
        public async Task<ContentChangeSet> UpdateFile(string relativePath, ContentItem item)
        {
            var fullPath = GetFullPath(relativePath);
            var existingItem = await this.GetAllContents(fullPath);
            if (existingItem == null || existingItem.Count == 0)
            {
                throw new FileNotFoundException(string.Format("Can't update \"{0}\", file doesn't exist", relativePath));
            }

            var response = await this._client.Repository.Content.UpdateFile(
                    this._ownerName,
                    this._repositoryName,
                    fullPath,
                    new UpdateFileRequest(string.Format("Update {0}", relativePath), Encoding.UTF8.GetString(item.ByteContent), existingItem[0].Sha));


            var createdItem = response.Content.ToContentItem();
            createdItem.Path = relativePath;

            var changeSet = new ContentChangeSet(response.Commit.Sha, new[] { new ContentItemInfo(createdItem) });
            return changeSet;
        }
		public void SaveContentItem(string path, ContentItem item)
		{
			var existingItem = ContentItems.FirstOrDefault(p => p.Path == path);
			if (existingItem != null)
			{
				existingItem.ByteContent = item.ByteContent;
				Update(existingItem);
			}
			else
			{
				item.Path = path;
				Add(item);
			}

			var steps = path.Split('/');
			if (steps.Length > 2)
			{
				var themePath = string.Join("/", steps[0], steps[1]);
				var theme = Themes.FirstOrDefault(t => t.Id == themePath);
				if (theme != null)
				{
					theme.ModifiedDate = DateTime.UtcNow;
					Update(theme);
				}
				else
				{
					theme = new Theme();
					theme.Id = themePath;
					theme.ThemePath = themePath;
					theme.Name = steps[1];
					theme.CreatedDate = DateTime.UtcNow;
					Add(theme);
				}
			}

			UnitOfWork.Commit();
		}
		public static ContentItem AsContentItem(this ThemeAsset asset)
		{
			var retVal = new ContentItem { Path = asset.Id, ByteContent = asset.ByteContent, ContentType = asset.ContentType, Name = Path.GetFileName(asset.AssetName) };

		    return retVal;
		}
		public async Task<bool> SaveContentItem(string path, ContentItem item)
		{
			var fullPath = GetFullPath(path);

			var existingItem = this.GetItem(fullPath).Result;

			var sha = String.Empty;

			if (existingItem == null) // create new
			{
				var response = await
					this._client.Repository.Content.CreateFile(
						this._ownerName,
						this._repositoryName,
						fullPath,
						new CreateFileRequest("Updating file from admin", Encoding.UTF8.GetString(item.ByteContent)));
			}
			else // update existing
			{
				var response = await
					this._client.Repository.Content.UpdateFile(
						this._ownerName,
						this._repositoryName,
						fullPath,
						new UpdateFileRequest("Updating file from admin", Encoding.UTF8.GetString(item.ByteContent), existingItem.Sha));
			}

			return true;
		}
		private ContentItem GetContentItem(string path, string storeId, string themePath)
		{
			var retVal = new ContentItem();

			var fullPath = GetFullPath(path, themePath);

			var itemName = Path.GetFileName(fullPath);
			retVal.ByteContent = File.ReadAllBytes(fullPath);
			retVal.Name = itemName;
			retVal.ContentType = ContentTypeUtility.GetContentType(fullPath, retVal.ByteContent);

			return retVal;
		}
        public void SaveContentItem(string path, ContentItem item)
        {
            var fullPath = GetFullPath(path);

            var existingItem = this.GetItem(fullPath);

            var sha = String.Empty;

            if (existingItem == null) // create new
            {
                var response = Task.Run(() =>
                    this._client.Repository.Content.CreateFile(
                        this._ownerName,
                        this._repositoryName,
                        fullPath,
                        new CreateFileRequest(string.Format("Create {0}", path), Encoding.UTF8.GetString(item.ByteContent)))).Result;
            }
            else // update existing
            {
                var response = Task.Run(() => this._client.Repository.Content.UpdateFile(
                        this._ownerName,
                        this._repositoryName,
                        fullPath,
                        new UpdateFileRequest(string.Format("Update {0}", path), Encoding.UTF8.GetString(item.ByteContent), existingItem.Sha))).Result;
            }
        }
		public Task<bool> SaveContentItem(string path, ContentItem item)
		{
			var fullPath = this.GetFullPath(path);

			var directoryPath = Path.GetDirectoryName(fullPath);
			if (!Directory.Exists(directoryPath))
			{
				Directory.CreateDirectory(directoryPath);
			}

			using (var fs = new FileStream(fullPath, FileMode.Create))
			{
				fs.Write(item.ByteContent, 0, item.ByteContent.Length);
				fs.Close();
			}

			return Task.FromResult(true);
		}