Skip to content

Instantly share code, notes, and snippets.

@wbbernardes
Created March 28, 2020 23:29
Show Gist options
  • Save wbbernardes/fa755031ed4e50e7a2dffda17df45d5d to your computer and use it in GitHub Desktop.
Save wbbernardes/fa755031ed4e50e7a2dffda17df45d5d to your computer and use it in GitHub Desktop.
//
// HomePresenter.swift
// javapop
//
// Created by Wesley Brito on 28/03/20.
// Copyright © 2020 Wesley Brito. All rights reserved.
//
import Foundation
protocol HomePresenterDelegate: AnyObject {
func repoFound(_ error: RequestErrors?)
}
class HomePresenter {
var githubItens: [Item] = []
weak var delegate: HomePresenterDelegate?
// MARK: - Api Request
func loadRepos(pageCount: Int = 1) {
ServiceConnection().makeHTTPGetRequest(ServiceRepository.baseUrl(page: pageCount), Github.self) { (result, error) in
self.githubItens += result?.items ?? []
self.delegate?.repoFound(error)
}
}
// MARK: - Get Infors
func getAvatarUrl(_ index: Int) -> URL? {
if let avatar = githubItens[index].owner?.avatarURL,
let image = URL(string: avatar) {
return image
}
return nil
}
func getUsername(_ index: Int) -> String {
if let username = githubItens[index].owner?.login {
return username
}
return ""
}
func getName(_ index: Int) -> String {
return githubItens[index].name
}
func getDescription(_ index: Int) -> String {
return githubItens[index].itemDescription
}
func getForkCount(_ index: Int) -> String {
return "\(githubItens[index].forksCount)"
}
func getStarsCount(_ index: Int) -> String {
return "\(githubItens[index].stargazersCount)"
}
func getFullName(_ index: Int) -> String {
return githubItens[index].fullName
}
func getHtmlUrl(_ index: Int) -> String {
return githubItens[index].htmlURL
}
func getItensCount() -> Int {
return githubItens.count
}
// MARK: - Filter
func filterRepo(searchText: String = "", sort: SortType = .Star) {
if !searchText.isEmpty {
let filtered = githubItens.filter{
($0.name.range(of: searchText, options: .caseInsensitive) != nil) ||
($0.owner!.login.range(of: searchText, options: .caseInsensitive) != nil)
}
self.githubItens = []
self.githubItens = filtered
} else if sort == .Star {
let filtered = githubItens.sorted { $0.stargazersCount > $1.stargazersCount }
self.githubItens = []
self.githubItens = filtered
} else {
let filtered = githubItens.sorted { $0.name.lowercased() < $1.name.lowercased() }
self.githubItens = []
self.githubItens = filtered
}
}
func searchTextIsValid(text: String) -> Bool {
if text.count < 30 {
return true
} else {
return false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment