//
//  CustomViewMarker.swift
//  NearbyStores
//
//  Created by DT Team on 7/1/18.
//  Copyright © 2018 Amine. All rights reserved.
//

import UIKit
import GoogleMaps
import BadgeSwift

class CustomViewStoreMarker: UIView {
    

    var imageUrl = ""
    var isHasPromo = false
    var object: Store? = nil
    var object0: User? = nil
    var badge: BadgeSwift? = nil
    var size  = 60
    
    func setup(marker: GMSMarker) {
       
        self.frame = CGRect(x: 0, y: 0, width: size + 10, height: size + 10)
        self.backgroundColor = .clear
        
        
        //setup the bottom shape for marker
        setupPentagon()
        
        
        let imageView = UIImageView()
        
        imageView.frame = CGRect(x: 0, y: 0, width: size , height: size )
        imageView.contentMode = .scaleAspectFill
        
        
        imageView.layer.borderColor = Colors.primaryColor.cgColor
        imageView.roundCorners(radius: imageView.frame.height/2)
        imageView.layer.borderColor = Colors.primaryColor.cgColor
        imageView.layer.borderWidth = 4
        imageView.backgroundColor = Colors.primaryColor
        
       
     
         self.addSubview(imageView)
        
        
        if let object = self.object {
            
    
            
            if object.listImages.count > 0 {
                
                if let first = object.listImages.first {
                    
                    let url = URL(string: first.url200_200)
                    
                    if let placeHolder = UIImage(named: "default_store_image") {
                        
                        imageView.kf.indicatorType = .activity
                        imageView.kf.setImage(with: url, placeholder: placeHolder, options: [.transition(.fade(0.2))])
                        UIGraphicsBeginImageContextWithOptions(self.frame.size, false, UIScreen.main.scale)
                        
                        self.layer.render(in: UIGraphicsGetCurrentContext()!)
                        let imageConverted: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
                        UIGraphicsEndImageContext()
                        marker.icon = imageConverted
                        
                        
                        imageView.kf.setImage(with: url, completionHandler: {
                            result in

                            UIGraphicsBeginImageContextWithOptions(self.frame.size, false, UIScreen.main.scale)
                            
                            self.layer.render(in: UIGraphicsGetCurrentContext()!)
                            let imageConverted: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
                            UIGraphicsEndImageContext()
                            
                            marker.icon = imageConverted
                            
                        })
                    }
                    
                }else{
                    if let img = UIImage(named: "default_store_image") {
                        imageView.image = img
                    }
                }
            }else{
                
                if let img = UIImage(named: "default_store_image") {
                    imageView.image = img
                }
            }
        
            
            if  self.badge == nil {
                
                self.badge = setupBadge()
                self.badge?.isHidden = true
                
                if object.nbrOffers > 0{
                    self.badge?.text = "\(object.nbrOffers)"
                    self.badge?.isHidden = false
                }
                
            }
            
            
        }else if let user = self.object0 {
            
            
            if let image = user.images {
                
                let url = URL(string: image.url200_200)
                
                if let placeHolder = UIImage(named: "profile_placeholder") {
                    
                    
                    imageView.kf.indicatorType = .activity
                    imageView.kf.setImage(with: url, placeholder: placeHolder, options: [.transition(.fade(0.2))])
                    UIGraphicsBeginImageContextWithOptions(self.frame.size, false, UIScreen.main.scale)
                    
                    self.layer.render(in: UIGraphicsGetCurrentContext()!)
                    let imageConverted: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
                    UIGraphicsEndImageContext()
                    marker.icon = imageConverted
                
                
                    imageView.kf.setImage(with: url, completionHandler: {
                        result in

                        UIGraphicsBeginImageContextWithOptions(self.frame.size, false, UIScreen.main.scale)
                        
                        self.layer.render(in: UIGraphicsGetCurrentContext()!)
                        let imageConverted: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
                        UIGraphicsEndImageContext()
                        
                        marker.icon = imageConverted
                        
                    })
                }
                
            }else{
                
                if let img = UIImage(named: "profile_placeholder") {
                    imageView.image = img
                }
            }
            
        }
        
        
    
    }
    
    
    func setupPentagon(){
       
        let pentagonView = UIImageView()
        pentagonView.frame = CGRect(x: 20, y: 52, width: 20, height: 20)
        pentagonView.contentMode = .scaleToFill
        pentagonView.tintColor = Colors.primaryColor
        
        let icon = UIImage(named: "pentagon")!.withRenderingMode(.alwaysTemplate)
        pentagonView.image = icon
    
        
        self.addSubview(pentagonView)
        
        pentagonView.widthAnchor.constraint(equalTo: widthAnchor, constant: 20).isActive = true
        pentagonView.heightAnchor.constraint(equalTo: heightAnchor, constant: 20).isActive = true
        
    }
    
    
    func setupBadge() -> BadgeSwift {
        
        let badge = BadgeSwift()
        self.addSubview(badge)
        
        // Text
        badge.text = "1"
        
        // Insets
        badge.insets = CGSize(width: 4, height: 4)
        
        // Font
        badge.initBolodFont(size: 14)
        
        // Text color
        badge.textColor = .white
        
        // Badge color
        badge.badgeColor = Colors.primaryColor
        
        // No shadow
        badge.shadowOpacityBadge = 0
        
        badge.borderWidth = 0
        badge.borderColor = Colors.primaryColor
        
        positionBadge(badge)
        
        return badge
    }
   
    
    private func positionBadge(_ badge: UIView) {
        
        badge.translatesAutoresizingMaskIntoConstraints = false
        var constraints = [NSLayoutConstraint]()
        
        constraints.append(NSLayoutConstraint(
            item: badge,
            attribute: NSLayoutConstraint.Attribute.right,
            relatedBy: NSLayoutConstraint.Relation.equal,
            toItem: self,
            attribute: NSLayoutConstraint.Attribute.right,
            multiplier: 1, constant: -5)
        )
        
        constraints.append(NSLayoutConstraint(
            item: badge,
            attribute: NSLayoutConstraint.Attribute.top,
            relatedBy: NSLayoutConstraint.Relation.equal,
            toItem: self,
            attribute: NSLayoutConstraint.Attribute.top,
            multiplier: 1, constant: 0)
        )
        
        self.addConstraints(constraints)
    }
    
}


class PentagonView : UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.green
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        backgroundColor = UIColor.green
    }

    override func draw(_ rect: CGRect) {
        let size = self.bounds.size
        let h = size.height * 0.85      // adjust the multiplier to taste

        // calculate the 5 points of the pentagon
        let p1 = self.bounds.origin
        let p2 = CGPoint(x:p1.x + size.width, y:p1.y)
        let p3 = CGPoint(x:p2.x, y:p2.y + h)
        let p4 = CGPoint(x:size.width/2, y:size.height)
        let p5 = CGPoint(x:p1.x, y:h)

        // create the path
        let path = UIBezierPath()
        path.move(to: p1)
        path.addLine(to: p2)
        path.addLine(to: p3)
        path.addLine(to: p4)
        path.addLine(to: p5)
        path.close()

        // fill the path
        //UIColor.red.set()
        path.fill()
    }
}
