import UIKit
import SDWebImage

class Stories_TableCell: UITableViewCell {
    
    @IBOutlet weak var storyTextLabel: UILabel!
    @IBOutlet weak var usernameLabel: UILabel!
    @IBOutlet weak var progressView: CircleProgress!
    
    override func awakeFromNib() {
        super.awakeFromNib()
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
    func setData(object: UserData) {
        if let name = object.name, name != "" {
            self.usernameLabel.text = name
        } else if let username = object.username, username != "" {
            self.usernameLabel.text = username
        } else {
            let name = [object.first_name ?? "", object.last_name ?? ""].filter({ $0 != "" }).joined(separator: " ")
            self.usernameLabel.text = name
        }
        self.storyTextLabel.text = self.timeStampStringToTime(timestampString: object.stories?.last?.posted ?? "")
        self.progressView.total = (object.stories?.count ?? 0)
        let url = URL.init(string: object.avatar ?? "")
        let indicator = SDWebImageActivityIndicator.medium
        self.progressView.progressImageView.sd_imageIndicator = indicator
        DispatchQueue.global(qos: .userInteractive).async {
            self.progressView.progressImageView.sd_setImage(with: url, placeholderImage: UIImage(named: ""))
        }
        self.progressView.setProgress(progress: CGFloat(object.stories?.filter({ $0.is_viewed == 1 }).count ?? 0))
    }
    
    func timeStampStringToTime(timestampString: String) -> String {
        let unixTimestamp = TimeInterval(timestampString) ?? 0
        let date = Date(timeIntervalSince1970: unixTimestamp)
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .full
        dateFormatter.timeStyle = .short
        let timeString = dateFormatter.string(from: date)
        return timeString
    }
    
}
